說起字符串函數,我想大家都不陌生。字符串函數對二進制數據、字符串和表達式執行不同的運算。下面總結了C語言中的字符串函數。
13、函數名: strncmpi
功 能: 把串中的一部分與另一串中的一部分比較, 不管大小寫
用 法:
- int strncmpi(char *str1, char *str2);
程序例:
- #include <string.h>
- #include <stdio.h>
- int main(void)
- {
- char *buf1 = "BBBccc", *buf2 = "bbbccc";
- int ptr;
- ptr = strncmpi(buf2,buf1,3);
- if (ptr > 0)
- printf("buffer 2 is greater than buffer 1\n");
- if (ptr < 0)
- printf("buffer 2 is less than buffer 1\n");
- if (ptr == 0)
- printf("buffer 2 equals buffer 1\n");
- return 0;
- }
14、函數名: strncpy
功 能: 串拷貝
用 法:
- char *strncpy(char *destin, char *source, int maxlen);
程序例:
- #include <stdio.h>
- #include <string.h>
- int main(void)
- {
- char string[10];
- char *str1 = "abcdefghi";
- strncpy(string, str1, 3);
- string[3] = '\0';
- printf("%s\n", string);
- return 0;
- }
15、函數名: strnicmp
功 能: 不注重大小寫地比較兩個串
用 法:
- int strnicmp(char *str1, char *str2, unsigned maxlen);
程序例:
- #include <string.h>
- #include <stdio.h>
- int main(void)
- {
- char *buf1 = "BBBccc", *buf2 = "bbbccc";
- int ptr;
- ptr = strnicmp(buf2, buf1, 3);
- if (ptr > 0)
- printf("buffer 2 is greater than buffer 1\n");
- if (ptr < 0)
- printf("buffer 2 is less than buffer 1\n");
- if (ptr == 0)
- printf("buffer 2 equals buffer 1\n");
- return 0;
- }
16、函數名: strnset
功 能: 將一個串中的所有字符都設為指定字符
用 法:
- char *strnset(char *str, char ch, unsigned n);
程序例:
- #include <stdio.h>
- #include <string.h>
- int main(void)
- {
- char *string = "abcdefghijklmnopqrstuvwxyz";
- char letter = 'x';
- printf("string before strnset: %s\n", string);
- strnset(string, letter, 13);
- printf("string after strnset: %s\n", string);
- return 0;
- }
17、函數名: strpbrk
功 能: 在串中查找給定字符集中的字符
用 法:
- char *strpbrk(char *str1, char *str2);
程序例:
- #include <stdio.h>
- #include <string.h>
- int main(void)
- {
- char *string1 = "abcdefghijklmnopqrstuvwxyz";
- char *string2 = "onm";
- char *ptr;
- ptr = strpbrk(string1, string2);
- if (ptr)
- printf("strpbrk found first character: %c\n", *ptr);
- else
- printf("strpbrk didn't find character in set\n");
- return 0;
- }
18、函數名: strrchr
功 能: 在串中查找指定字符的最後一個出現
用 法:
- char *strrchr(char *str, char c);
程序例:
- #include <string.h>
- #include <stdio.h>
- int main(void)
- {
- char string[15];
- 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-string);
- else
- printf("The character was not found\n");
- return 0;
- }
19、函數名: strrev
功 能: 串倒轉
用 法:
char *strrev(char *str);
程序例:
- #include <string.h>
- #include <stdio.h>
- int main(void)
- {
- char *forward = "string";
- printf("Before strrev(): %s\n", forward);
- strrev(forward);
- printf("After strrev(): %s\n", forward);
- return 0;
- }