C語言編寫 刪除字串中的子串
阿新 • • 發佈:2019-01-06
輸入2個字串S1和S2,要求刪除字串S1中出現的所有子串S2,即結果字串中不能包含S2。
輸入格式:
輸入在2行中分別給出不超過80個字元長度的、以回車結束的2個非空字串,對應S1和S2。
輸出格式:
在一行中輸出刪除字串S1中出現的所有子串S2後的結果字串。
輸入樣例:Tomcat is a male ccatat cat輸出樣例:
Tom is a male
#include<string.h> #include<stdio.h> int main(){ char str[200]; char str_d[200]; char tmp[200]; int i, len_str, len_str_d; fgets(str, sizeof(str), stdin); fgets(str_d, sizeof(str_d), stdin); len_str = strlen(str) - 1; str[len_str] = 0; len_str_d = strlen(str_d) - 1; str_d[len_str_d] = 0; i = 0; while(str[i] != 0){ if(str[i] == str_d[0]){ strncpy(tmp, str+i, len_str_d); tmp[len_str_d] = 0; if(!strcmp(tmp, str_d)){ str[i] = 0; strcat(str, str + i + len_str_d); i = 0; continue; } } ++i; } printf("%s\n", str); return 0; }
`fgets'--get character string from a file or stream
從檔案或者流中獲取字串
stdin是標準輸入流
char *strncpy( char *to, const char *from, size_t count ); 功能:將字串from 中至多count個字元複製到字串to中。如果字串from 的長度小於count,其餘部分用'\0'填補。返回處理完成的字串。
strcmp這是一個字串比較函式,如果兩個字串相等,則返回0,if(!strcmp(str1,str2))這個語句的意思就是如果這個兩個字串相等,就執行後面的語句。
strcat(p1,p2)就是把p2所指的字串,連線到p1後面。 如char *p1="ab",char *p2="cd"; strcat(p1,p2)後,則p1指向"abcd", strcat返回的是p1的指標。 strcpy就是把些時p1所指的內容,放在str+2的位置上。 比如str指向"xyz", 則strcpy後,str指向值為“xyabcd