Обработка строк - часть 2
ptr = strncmp(buf2,buf3,3); if (ptr > 0) printf("buffer 2 is greater than buffer 3\n"); else printf("buffer 2 is less than buffer 3\n"); getch(); return(0); }
strcpy - копировать строку s2 в строку s1.
Определение: char *strcpy(s1,s2) char *s1, *s2;
Пример 5:
#include <stdio.h> #include <string.h> #include <conio.h> int main(void) { clrscr(); char string[10]; char *str1 = "abcdefghi";
strcpy(string, str1); printf("%s\n", string); getch(); return 0; }
strncpy - копировать не более n символов строки s2.
Определение: char *strncpy(s1,s2,n) char *s1, *s2; int n;
Пример 6:
#include <stdio.h> #include <string.h> #include <conio.h> int main(void) { clrscr(); char string[10]; char *str1 = "abcdefghi"; strncpy(string, str1, 3); string[3] = '\0'; printf("%s\n", string); getch(); return 0; }
strlen - определить длину строки (число символов без завершающего нулевого символа).
Определение: int strlen(s) char *s;
Пример 7:
#include <stdio.h> #include <string.h> #include <conio.h> int main(void) { clrscr(); char *string = "Borland International"; printf("%d\n", strlen(string)); getch(); return 0; }
strchr - найти в строке первое вхождение символа с.
Определение: char *strchr(s,n) char *s; int n;
Пример 8:
#include <string.h> #include <stdio.h> #include <conio.h> int main(void) { clrscr(); char string[20]; char *ptr, c = 'r'; strcpy(string, "This is a string"); ptr = strchr(string, c); if (ptr) printf("The character %c is at position: %d\n", c, ptr); else printf("The character was not found\n"); getch(); return 0; }
strrchr - найти в строке последнее вхождение символа с.
Определение: char *strrchr(s,c) char *s; int c;
Пример 9:
#include <string.h> #include <stdio.h> #include <conio.h> int main(void) { clrscr(); char string[20]; char *ptr, c = 'r'; strcpy(string, "This is a string"); ptr = strrchr(string, c); if (ptr) printf("The character %c is at position: %d\n", c, ptr); else printf("The character was not found\n"); getch(); return 0; }