對給定字符串刪除特定字符或者是特定字符串。對字符串操做必定要注意結束符'\0'的處理。spa
// StrDeleteChar.cpp : 定義控制檯應用程序的入口點。 // #include "stdafx.h" void StrDeleteChar(char *str, char ch) {//刪除字符串str中的指定字符ch int i, j; for (i = 0,j = 0; str[i] != '\0'; i++) { if (str[i] != ch) { str[j++] = str[i]; } } str[j] = '\0'; } void StrDeleteWord(char *str, char *wd) {//刪除字符串中str中的指定單詞wd int i,j,k; int len = strlen(wd); for (i=0,j=0,k=0; str[i] != '\0'; i++) { //字符不相等 if (str[i] != wd[j]) { str[k++] = str[i]; j = 0; } else { while (str[i] == wd[j] && j < len) { i++; j++; } //匹配 if (j == len) { //str[k] = str[i]; j = 0; --i; } else //不匹配 { i = i- j; j = 0; str[k++] = str[i]; } } } str[k] = '\0'; } int _tmain(int argc, _TCHAR* argv[]) { char str[] = "I amtion a student, haha"; StrDeleteChar(str, 'a'); printf("After delete :%s\n", str); char str1[] = "Hello world,I amamam here am haha."; char wd[] = "am"; StrDeleteWord(str1,wd); printf("After delete word: %s,the result is:%s\n",wd,str1); return 0; } 2014/4/16 20:40