C语言 如何删除输出中多余的换行符?

ymdaylpp  于 2023-11-16  发布在  其他
关注(0)|答案(3)|浏览(162)

反向字符串程序:

/**
 * 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


我试图扭转一个字符串的字,但扭转字符串是不是打印在同一行。

scyqe7ek

scyqe7ek1#

fgets gets读取输入行,包括按Enter键导致的换行符。因此,如果输入stack overflow,则str的实际内容变为stack overflow\n

if (len > 0 && str[len - 1] == '\n') {
    str[len - 1] = '\0';
    len--;
}

字符串

bttbmeg0

bttbmeg02#

或者,您可以使用:用途:

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

字符串
从字符串中去掉换行符。

tf7tbtn2

tf7tbtn23#

另一个(简单的)替代方案可以完成工作:

(void)strtok( str, "\n" ); // trim LF from end of string

字符串
使用(void)来证明你知道你在做什么。
(PS:在AFTER从字符串的末尾修剪LF之前,不要调用strlen().)

相关问题