Как поменять местами две буквы в строке char []? - PullRequest
0 голосов
/ 19 декабря 2018

Извините за заголовок, но я не знаю, как называется эта программа.

Я пытаюсь написать программу, которая принимает параметр int, и вывести слово длины nнапример, из букв «а» и «б»:

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 голосов
/ 19 декабря 2018

Просто сделайте 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) и удалить.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...