重新排列字符串字母

Rearranging string letters

我正在编写一个程序来复制除前 2 个单词之外的所有字符串单词并在其末尾放置一个 x。 但是我不能把 x 放在最后。请帮忙!!!! 下面是我的代码。

#include<stdio.h>
#include<string.h>

int main()
{
    char a[25], b[25];
    int i, j, count = 0, l, k;
    scanf("%[^\n]s", a);
    i = strlen(a);
    if (i > 20)
        printf("Given Sentence is too long.");
    else
    {/* checking for first 2 words and counting 2 spaces*/
        for (j = 0; j < i; j++)
        {
            if (a[j] == ' ')
                count = count + 1;
            if (count == 2)
            {
                k = j;
                break;
            }
        }

        /* copying remaining string into new one*/
        for (j = 0; j < i - k; j++)
        {
            b[j] = a[j + k];
        }
        b[j + 1] = 'x';
        printf("%s", b);
    }
}

你的指数差了一位。在你的第二个循环之后,条件 j < i-k 为假,所以 j 现在 i-k。因此,您复制的内容结束后的字符是b[j],而不是b[j+1]。因此,正确的行应该是 b[j] = 'x';.

只是改变它会给你留下不是 字符串的东西。 string 定义为 char 的序列,以 '[=18=]' 字符结尾。所以你来添加b[j+1] = 0;

进行这些更改后,您的代码会按预期运行,但仍然存在未定义的行为。


一个问题是您的 scanf() 会很高兴地溢出您的缓冲区 -- 在此处使用 字段宽度 scanf("%24[^\n]", a);。顺便说一下,and处的s没有任何意义,你用或者s转换成或者 [] 转换。


一个比较明智的实现是使用适合该工作的功能,例如这个:

#include<stdio.h>
#include<string.h>

int main(void)
{
    // memory is *cheap* nowadays, these buffers are still somewhat tiny:
    char a[256];
    char b[256];

    // read a line
    if (!fgets(a, 256, stdin)) return 1;
    // and strip the newline character if present
    a[strcspn(a, "\n")] = 0;

    // find first space
    char *space = strchr(a, ' ');

    // find second space
    if (space) space = strchr(space+1, ' ');

    if (space)
    {
        // have two spaces, copy the rest
        strcpy(b, space+1);
        // and append 'x':
        strcat(b, "x");
    }
    else
    {
        // empty string:
        b[0] = 0;
    }

    printf("%s",b);
    return 0;
}

对于你不知道的函数,google对于man <function>

如您所知,在 C 中,字符串是字符数组,C 知道它是字符串结尾的方式是 '\0' 字符。在您的示例中,您缺少最后几行

/* copying remaining string into new one*/
 for(j=0;j<i-k;j++)
 {
     b[j]=a[j+k];
 }
 b[j+1]='x';
 printf("%s",b);

循环结束后j在退出循环前已经加1

所以如果你在 x 之前的字符串是 "test",就像 't', 'e', 's', 't','\0' 在 char 数组中,并且由于你的 j 增加了超过它应该有的,它到达了这一点'\0' 右边,但 '\0' 之后的字符无关紧要,因为它是结尾,所以不会添加你的 x。简单更改为

b[j]='x';

您要删除前两个索引。但是你写了 k=j 并且如果你检查当前值 j 那里它是 1. 所以你更新错误 k 因为你删除了 2 个索引。所以k值应该是2。所以检查了下面的代码

/* copying remaining string into new one*/
        for (j = 0; j < i - 2; j++)
        {
            b[j] = a[j + 2];
        }
        b[j + 1] = 'x';
        printf("%s", b);