Remove spaces and blanks in the head and tail of a string
#include <iostream>
using namespace std;
void strtrim(char *str)
{
if(str == NULL){
return;
}
// trim right
char *p = str;
while(*p != '\0'){
p ++;
}
p --;
while(p >= str && (*p == '\t' || *p == ' ' || *p == '\n')){
p --;
}
*(p + 1) = '\0';
p = str;
while(*p != '\0' && (*p == '\t' || *p == ' ' || *p == '\n')){
p ++;
}
// move
char *p1 = str;
while(*p != '\0'){
*p1++ = *p++;
}
*p1 = '\0';
}
int main(int argc, char* argv[])
{
char strs[5][100] = {
"string",
" united states ",
" standard template\t library\t ",
"\t\t hello, word\t\n ",
""
};
for(int i = 0; i < 5; i++){
cout << strs[i] << "stop" << endl;
strtrim(strs[i]);
cout << strs[i] << "stop" << endl;
}
return 0;
}
Output
stringstop
stringstop
united states stop
united statesstop
standard template library stop
standard template librarystop
hello, word
stop
hello, wordstop
stop
stop