最近做題遇到分割與匹配字符串的題目(hdu5311),看來別人的代碼,才知道有strncpy()和strstr()函數,於是搜集了一點資料,記錄一下基本用法。
一、strncpy()
char * strncpy ( char * destination, const char * source, size_t num );
strncpy() 在 <string.h>頭文件中(C++中為<cstring>),拷貝原字符串S中長度為num的部分至目標字符串D中。
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "hello world";
char str1[20];
char str2[20];
// 拷貝source中從0到5的字符串
strncpy(str1, source, 6); // 0~5: 長度為6
puts(str1);
// 運行后結果為 hello
// 拷貝source中從1到5的字符串
strncpy(str2, source+1, 5); // 1~5: 長度為5
puts(str2);
// 運行后結果為 ello
// 原字符串不變
puts(source);
// 運行后結果為 hello world
return 0;
}
分割字符串中,原字符串是不會改變的,同時分割的起點是通過指針控制的,而結束點則是通過長度間接決定的,使用時需要注意。
二、strstr()
const char * strstr ( const char * str1, const char * str2 );
char * strstr ( char * str1, const char * str2 );
其中str1是原字符串,str2是帶匹配的字符串,放回第一次str2出現的位置(指針)
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "hello world hello world";
char str1[] = "hello";
char *str2;
// 查找第一個hello出現的位置
printf("%d\n", strstr(source, str1) - source);
// 運行后結果為0
// 查找第一個world出現的位置
str2 = strstr(source, "world");
printf("%d\n", str2 - source);
// 運行后結果為6
// 查找第二個world出現的位置
printf("%d\n", strstr(source + (str2 - source) + 1, "world") - source);
// 運行后結果為18
return 0;
}
因為返回的是指針,如果需要計算位置的話,可以通過指針相減的方式,進行計算得到。
因為返回的時第一次找到的位置,所以要想找到第N次(N > 1)出現的位置,就要從第N-1次出現的位置+1處開始尋找。
