Today I wrote a small program to remove the extra spaces in the string, such as "i___am_____a______student." (Underline for empty Geha, dozen spaces to display or one), and final output "I am a student."
Now put your own ideas posted on, Welcome to comment.
The idea is to define two pointers next and tail, one to look for non whitespace characters in the front, another to move in the back step by step, all the characters in the back to the front, and then to remove the extra space, where there are multiple or a space, to leave a space.
#include <iostream>
using namespace std;
char * deletespace (char * str) {
char * tail = str;
char * next = str;
while (*next) {//Two if can be merged together so that it is written simply to look at the convenience
if (*next!= ') {//Find characters that are not spaces
*tail = *next;
tail++;
}
if (*next = = ' && * (next-1)!= ') {//the judgment condition of leaving only one space; The current character is a space and the previous one is not a space.
*tail = *next;
tail++;
}
next++;
}
*tail= ' "; String end return
str;
}
int main () {
char str[] = "I am a student.";
Char *res = deletespace (str);
cout << res << Endl;
return 0;
}