2025年3月28日 星期五 甲辰(龙)年 月廿七 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

C语言中使字符串右对齐的方法

时间:12-30来源:作者:点击数:137

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()函数的工作过程如下所示:

  1. 将原字符串的长度存到变量n中。这一步是不可缺少的,因为输出字符串和原字符串的长度必须相同。
  2. 调用标准C库函数strdup(),将原字符串复制到dup_str中。原字符串需要有一份拷贝,因为经过右对齐处理的字符串要写到原字符串中。
  3. 调用rtrim()函数,删去dup_str尾部的空格。
  4. 调用标准C库函数sprinf(),将dup_str写到原字符串中。由于原字符串的长度(存在n中)被传递给sprintf()函数,所以迫使输出字符串的长度和原字符串相同。因为sprintf()函数缺省使输出字符串右对齐,因此输出字符串的头部将被加入空格,以使它和原字符串长度相同,其效果实际上就是使原字符串右对齐。
  5. 调用标准库函数free(),释放由strdup()函数分配给dup_str的动态内存。
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门