对于字符串增加类型:
先算出新的长度,然后一个一个赋值:
#include <iostream> #include <string> void change_word(char *a, int len) { if (a == NULL) { return; } int count = 0; for (int i=0; i<len; i++) { if (a[i] == ‘ ‘) { count+=2; } } int newi = len + count - 1; for (int i=len-1; i>=0; i--) { if (a[i] != ‘ ‘) { a[newi--] = a[i]; } else { a[newi--] = ‘3‘; a[newi--] = ‘2‘; a[newi--] = ‘1‘; } } return; } int main() { std::cout << "Hello, World!" << std::endl; char ch[100]; strncpy(ch, "hi hi hihihi hi", 16); std::cout << ch << std::endl; change_word(ch, 16); std::cout << ch << std::endl; return 0; }
对于字符串长度减少,直接替换。(略)
对于重复字符只留一个,下面的解法,直接位置放置:
#include <iostream> #include <string> void change_word(char *a) { if (a == NULL) { return; } int newi = 0; int i = 0; while (a[i] != ‘\0‘) { if (i==0 || a[i] != a[i-1]) { if (newi != i) { a[newi] = a[i]; } newi++; } i++; } a[newi] = ‘\0‘; return; } int main() { std::cout << "Hello, World!" << std::endl; char ch[100]; strncpy(ch, "hi hhi hiiiiihhhihi hi", 23); std::cout << ch << std::endl; change_word(ch); std::cout << ch << std::endl; return 0; }
原文:http://www.cnblogs.com/charlesblc/p/6414369.html