Posted on 2008-12-30 16:48
Prayer 閱讀(1794)
評論(0) 編輯 收藏 引用 所屬分類:
C/C++
/ * The rtrim() function removes trailing spaces from a string. * /.
char * rtrim(char * str)
{
int n = strlen(str)-1; / * Start at the character BEFORE
the null character (\0). * /
while (n>0) / * Make sure we don’t go out of hounds. . . * /
{
if ( * (str + n) 1 =’ ’) / * If we find a nonspace character: * /
{
* (str+n+1) = ’\0’ ; / * Put the null character at one
character past our current
position. * /
break ; / * Break out of the loop. * /
}
else / * Otherwise , keep moving backward in the string. * /.
n--;
}
return str; /*Return a pointer to the string*/
}
在上例中,rtrim()是用戶編寫的一個函數,它可以刪去字符串尾部的空格。函數rtrim()從字符串中位于null字符前的那個字符開始往回檢查每個字符,當遇到第一個不是空格的字符時,就將該字符后面的字符替換為null字符。因為在C語言中null字符是字符串的結束標志,所以函數rtrim()的作用實際上就是刪去字符串尾部的所有空格。