字符串操作
对给定字符串删除特定字符或者是特定字符串。对字符串操作一定要注意结束符'\0'的处理。
// 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
我是一名在校大学生,热爱编程,虽然起步晚了些,但我会努力的。呵呵!
数据结构 算法