C语言中删去字符串尾部的空格的方法
C语言没有提供可删去字符串尾部空格的标准库函数,但是,编写这样的一个函数是很方便的。请看下例:
#include <stdio. h>
# include <string. h>
void main (void);
char * rtrim(char * );
void main(void)
{
char * trail_str = "This string has trailing spaces in it";
/ * Show the status of the string before calling the rtrim()
function. * /
printf("Before calling rtrim(), trail_str is '%s'\fi" , trail_str);
print ("and has a length of %d. \n" , strlen (trail_str));
/ * Call the rtrimO function to remove the trailing blanks. * /
rtrim(trail_str) ;
/ * Show the status of the string
after calling the rtrim() function. * /
printf("After calling rttim(), trail_ str is '%s'\n", trail _ str );
printf ("and has a length of %d. \n" , strlen(trail-str)) ;
}
/ * 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()的作用实际上就是删去字符串尾部的所有空格。
#include <stdio. h>
# include <string. h>
void main (void);
char * rtrim(char * );
void main(void)
{
char * trail_str = "This string has trailing spaces in it";
/ * Show the status of the string before calling the rtrim()
function. * /
printf("Before calling rtrim(), trail_str is '%s'\fi" , trail_str);
print ("and has a length of %d. \n" , strlen (trail_str));
/ * Call the rtrimO function to remove the trailing blanks. * /
rtrim(trail_str) ;
/ * Show the status of the string
after calling the rtrim() function. * /
printf("After calling rttim(), trail_ str is '%s'\n", trail _ str );
printf ("and has a length of %d. \n" , strlen(trail-str)) ;
}
/ * 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()的作用实际上就是删去字符串尾部的所有空格。