* (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()
的作用实际上就是删去字符串尾部的所有空格。
请参见:
6.3 怎样删去字符串头部的空格?
6.5 怎样将字符串打印成指定长度?
6.3 怎样删去字符串头部的空格?
C 语言没有提供可删去字符串头部空格的标准库函数,但是,编写这样的一个函数是
很方便的。请看下例;
#include <stdio. h>
#include <string. h>
void main(void);
char * ltrim (char * ) ;
char * rtrim(char * ) ;
void main (void)
{
char * lead_str = " This string has leading spaces in it. " ;,
/ * Show the status of the string before calling the Itrim()
function. * /
printf("Before calling Itrim(), lead-str is '%s'\n", lead_str);
printf("and has a length of %d. \n" , strlen(lead_str));
/ * Call the Itrim() function to remove the leading blanks. * /.
Itrim(lead_str);
/ * Show the status of the string
after calling the Itrim() function. * /
prinft("After calling Itrim(), lead_str is '%s'\n", lead_str);
print("and has a length of %d. \n'' , strlen(lead-str)) ;
}
/ * The Itrim() function removes leading spaces from a string. * /
char * ltrim(char * str)
{
strrev(str) ; / * Call strrevO to reverse the string. * /