如何在字符串char []中的两个字母之间交换?

时间:2018-12-18 21:48:51

标签: c

对不起,标题,但是我不知道这个程序叫什么。

我正在尝试编写一个程序,该程序带有一个int参数,并打印一个长度为n的单词,该单词由字母“ a”和“ b”组成 例如:

n= 3 
the result =>: `aaa,baa,aba,aab,bba,bab,abb,bbb`

这是我的代码。里面有问题:

#include <stdio.h>
#include <stdlib.h>

#define n  5

char word[n] = "aaa";
char noob[n];

void
myfunction(void)
{
    int x,
     i,
     j;

    for (i = 0; i < n - 1; i++) {
        // I did this to convert first from a char to int and then add one in
        // order to change a to b
        x = word[i];
        x++;
        word[i] = x;
        puts(word);

        // here is the problem after going through the first loob (i) we have
        // the word baa and it should go through the second loop j but it
        // doesn't
        for (j = 0; j < n - 1; j++) {
            noob[j] = word[j];
            word[j + 1] = word[j];
            word[j] = noob[j];
            puts(word);
        }

    }
}

int
main(void)
{
    myfunction();

    return 0;
}

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

只需char word[n] = "aaaaa";

完整代码:

#include <stdio.h>
#include <stdlib.h>

#define n  5

char word[n] = "aaaaa";
char noob[n];

void
myfunction(void)
{
    int x, i, j;

    for (i = 0; i < n - 1; i++) {
        // I did this to convert first from a char to int and then add one in
        // order to change a to b
        x = word[i];
        x++;
        word[i] = x;
        puts(word);

        // here is the problem after going through the first loob (i) we have
        // the word baa and it should go through the second loop j but it
        // doesn't
        for (j = 0; j < n - 1; j++) {
            noob[j] = word[j];
            word[j + 1] = word[j];
            word[j] = noob[j];
            puts(word);
        }

    }
}

int
main(void)
{
    myfunction();

    return 0;
}

当您在编译时知道单词的长度时,此功能当然可以工作。该长度仅在运行时(例如,用户输入时)才知道,您需要动态分配(例如,使用malloc)并删除。