http://www.cplusplus.com/reference/cstring/strstr/?kw=strstr
有兩個關於字串操作的函數相當有用,一個是strstr,比較str2是否在str1中,有的話傳回在str1的指標位址,如下:
strstr
const char * strstr ( const char * str1, const char * str2 ); char * strstr ( char * str1, const char * str2 );
Locate substring
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.The matching process does not include the terminating null-characters, but it stops there.
|
This example searches for the "simple" substring in str and replaces that word for "sample".
Output:
This is a sample string
另外就是常用的strcpy,若source指定的位置在字串中間時,會從指定的位置開始拷貝到字串的結尾(\0)處。
strcpy
char * strcpy ( char * destination, const char * source );
Copy string
Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> char str[300]={'\0'}; char find[10][100]={'\0'}; char replace[10][100]={'\0'}; char str1[300]={'\0'}; char str2[300]={'\0'}; char str3[300]={'\0'}; int main(){ freopen("input.txt", "r", stdin); int n; while(1){ scanf("%d",&n); getchar(); //printf("n=%d\n",n); if(n==0)break; int tmp=n; while(n--){ //輸入所有find和replace-by //printf("%d",n); gets(find[tmp-n-1]); gets(replace[tmp-n-1]); } /* for(int i=0;i<tmp;i++){ puts(find[i]); puts(replace[i]); } */ gets(str); //輸入要檢驗的字串 //puts(str); //getchar(); //printf("test"); for(int i=0;i<tmp;i++){ if(strstr(str,find[i])!=NULL){ char *pch = strstr(str,find[i]); int len = strlen(find[i]); strcpy(str1,pch+len); *pch = '\0'; strcat(str,replace[i]); strcat(str,str1); i--; //puts(str); } } puts(str); } return 0; }
沒有留言:
發佈留言