You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决C语言单词反转程序输出中的多余换行问题?

解决C语言字符串单词反转后的多余换行问题

问题场景

编写了一段实现字符串单词反转的C语言程序,但运行后反转后的字符串出现多余换行,无法在同一行显示。

原代码

/**
 * C program to reverse order of words in a string
 */
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
    char str[100], reverse[100];
    int len, i, index, wordStart, wordEnd;

    printf("Enter any string: ");
    fgets(str,sizeof(str),stdin);

    len   = strlen(str);
    index = 0;

    // Start checking of words from the end of string
    wordStart = len - 1;
    wordEnd   = len - 1;

    while(wordStart > 0)
    {
        // If a word is found
        if(str[wordStart] == ' ')//means blank space
        {
            // Add the word to the reverse string
            i = wordStart + 1;
            while(i <= wordEnd)
            {
                reverse[index] = str[i];

                i++;
                index++;
            }
            reverse[index++] = ' ';

            wordEnd = wordStart - 1;
        }

        wordStart--;
    }

    // Finally add the last word
    for(i=0; i<=wordEnd; i++)
    {
        reverse[index] = str[i];
        index++;
    }

    // Add NULL character at the end of reverse string
    reverse[index] = '\0'; 

    printf("Original string:%s\n\n", str);
    printf("Reverse  string:%s", reverse);

    return 0;
}

实际运行输出

Enter any string: stack overflow
Original string: stack overflow
Reverse  string: overflow
stack

期望输出

Enter any string: stack overflow
Original string: stack overflow
Reverse  string: overflow stack

问题原因

问题出在fgets函数的特性:它会把用户输入结束时按下的换行符\n也读取到字符串str中。当程序处理最后一个单词时,这个换行符被包含到了reverse字符串里,导致输出时出现换行。

解决方案

在获取字符串后,先去除str末尾的换行符,有两种简单的方式:

方法1:使用strcspn函数

在调用strlen之前添加一行代码:

str[strcspn(str, "\n")] = '\0';

strcspn会返回字符串中第一个\n字符的位置,直接将该位置设为字符串结束符\0,就能去掉换行符。

方法2:手动检查并替换

同样在strlen之前添加:

len = strlen(str);
if (len > 0 && str[len-1] == '\n') {
    str[len-1] = '\0';
    len--; // 更新字符串长度,避免后续处理出错
}

修改后的完整代码

/**
 * C program to reverse order of words in a string
 */
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
    char str[100], reverse[100];
    int len, i, index, wordStart, wordEnd;

    printf("Enter any string: ");
    fgets(str,sizeof(str),stdin);

    // 去除fgets读取的换行符
    str[strcspn(str, "\n")] = '\0';
    
    len   = strlen(str);
    index = 0;

    // Start checking of words from the end of string
    wordStart = len - 1;
    wordEnd   = len - 1;

    while(wordStart > 0)
    {
        // If a word is found
        if(str[wordStart] == ' ')//means blank space
        {
            // Add the word to the reverse string
            i = wordStart + 1;
            while(i <= wordEnd)
            {
                reverse[index] = str[i];

                i++;
                index++;
            }
            reverse[index++] = ' ';

            wordEnd = wordStart - 1;
        }

        wordStart--;
    }

    // Finally add the last word
    for(i=0; i<=wordEnd; i++)
    {
        reverse[index] = str[i];
        index++;
    }

    // Add NULL character at the end of reverse string
    reverse[index] = '\0'; 

    printf("Original string:%s\n\n", str);
    printf("Reverse  string:%s", reverse);

    return 0;
}

修改后运行输出

Enter any string: stack overflow
Original string: stack overflow
Reverse  string: overflow stack

内容的提问来源于stack exchange,提问作者Krinesh Vasava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 00:01:03