C语言没有提供可使字符串右对齐的标准库函数,但是,编写这样的一个函数是很方便的。请看下例:
- #include <stdio.h>
- #include <string.h>
- #include <malloc.h>
- char * rjust (char * );
- char * rtrim(char * );
- void main (void)
- {
- char * rjust_str = "This string is not righ-justified. " ;
- /* Show the status of the string before calling the rjust() function. */
- printf("Before calling rjust(), rjust_str is ' %s'\n. " , rjust_str);
- /* Call the rjustO function to right-justify this string. */
- rjust(rjust_str) ;
- /* Show the status of the string after calling the rjust() function. */
- printf ("After calling rjust() , rjust_str is ' %s'\n. " , rjust_str) ;
- }
- /* The rjust() function right-justifies a string. */
- char * r just (char * str)
- {
- int n = strlen(str); /* Save the original length of the string. */
- char* dup_str;
- dup_str = strdup(str); /* Make an exact duplicate of the string. */
- rtrim(dup_str); /* Trim off the trailing spaces. */
- /* Call sprintf () to do a virtual "printf" back into the original
- string. By passing sprintf () the length of the original string,
- we force the output to be the same size as the original, and by
- default the sprintf() right-justifies the output. The sprintf()
- function fills the beginning of the string with spaces to make
- it the same size as the original string. */
- sprintf(str, "%*. * s", n, n, dup_str);
- free(dup-str) ; /* Free the memory taken by the duplicated string. */
- 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)-l; /* 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. */
- }
在上例中,使字符串右对齐的工作是由用户编写的rjust()函数完成的,该函数调用了6.2的例子中的rtrim()函数和几个标准函数。rjust()函数的工作过程如下所示: