C语言没有提供可删去字符串头部空格的标准库函数,但是,编写这样的一个函数是很方便的。请看下例:
#include <stdio.h>
#include <string.h>
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. */
ltrim(lead_str);
/* Show the status of the string after calling the Itrim() function. */
printf("After calling Itrim(), lead_str is '%s'\n", lead_str);
printf("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. */
rtrim(str); /* Call rtrimO to remvoe the "trailing" spaces. */
strrev(str); /* Restore the string's original order. */
return str ; /* Return a pointer to the string. */
}
/* 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 bounds... */
{
if ( * (str+n)!=' ') /*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. */
}
在上例中,删去字符串头部空格的工作是由用户编写的ltrim()函数完成的,该函数调用了·6.2的例子中的rtrim()函数和标准C库函数strrev()。ltrim()函数首先调用strrev()函数将字符串颠倒一次,然后调用rtrim()函数删去字符串尾部的空格,最后调用strrev()函数将字符串再颠倒一次,其结果实际上就是删去原字符串头部的空格。