我有这样的输入:
" aaaaa bbb \n cccccc\n ddddd \neeee "
我需要像这样消毒:
"aaaaa bbb cccccc ddddd neeee"
基本上:
有没有简单的方法可以做到这一点,或者我必须处理字符串,char by char并将相应的字符复制到另一个变量?
答案 0 :(得分:3)
假设您无法修改字符串,
void splcpy(char *s, char *m){ //s is the unmodified string
int word = -1; //keeps track what was stored in last loop
while(*s){ //until it ends
if(!isspace(*s)){
if(word==0) *m++ = ' '; //if last char was space, add space
*m++ = *s++;
word = 1;
}
else{
if(word == 1) word = 0; //if last char was !space
while(isspace(*s++)); //consume all space until end
}
}
*m = '\0'; //end the string nicely
}
char *input = " aaaaa bbb \n cccccc\n ddddd \neeee ";
char *modified = malloc(sizeof(char) * strlen(input));
splcpy(input, modified);
答案 1 :(得分:0)
你可以使用strtok来词法化字符串,用“\ r \ n \ t”分隔。 这将使您的工作更轻松。