[英]How to swap between two letters in a string char[]?
对不起,标题,但是我不知道这个程序叫什么。
我正在尝试编写一个带有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;
}
有人能帮助我吗 ???
只是做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
)并删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.