字符串的处理,求教怎样写更好?
比如题目为怎样把字符串 "Hello world! This is c/c++! "里的空格数出来,并且处理成" Helloworld!Thisisc/c++!"?
想了半天憋出如下代码,感觉很累赘,,请教有无更好的方法?而且这里的字符串在处理的时候好不好?调试的时候常看到乱码,所幸输出没有.....
#include <stdio.h>#include <stdlib.h>void main(){ char * str="Hello world! This is c/c++! "; int i = 0; int j = 0; int count = 0; int len = 0; for(i=0; str[i] != '\0'; i++) len += 1; char str2[50]; for(i=0; i <= len; i++) { if(' ' == str[i]) { count +=1; } } for(i=0; i < count; i++) { str2[i] = ' '; } for(i=0; i <= len; i++) { if(' ' != str[i]) { str2[count++] = str[i]; } } printf("str2 is %s ", str2); }#include <stdio.h>int main(void){ char *str="Hello world! This is c/c++! "; char *p; int i, j, len; len = strlen(str); p = (char *)malloc(len + 1); for(i = 0, j = 0; i < len; ++i) { if(str[i] != ' ') { p[j] = str[i]; j++; } } printf("%s\n", p); free(p); return 0;}
[解决办法]
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
int main()
{
string str("Hello world! This is c/c++! ");
string::iterator iter=str.begin ();
for(;iter!=str.end();){
if(isspace(*iter))
iter=str.erase(iter);
else
++iter;
}
cout<<str<<endl;
}
这是我在VS2010下写的,希望对你有帮助
[解决办法]
#include<stdio.h>#include<stdlib.h>int func(char *buf){ int cnt = 0; char *read = buf; while ((' ' == *read) ? (++cnt, *read++) : (*buf++ = *read++)); return cnt;}int main(){ char a[] = "Hello world! This is c/c++! "; printf("%d\n", func(a)); printf("%s\n", a); system("pause"); return 0;}