[英]How to swap between two letters in a string char[]?
Sorry for the title, but I don't know what is this program called. 对不起,标题,但是我不知道这个程序叫什么。
I'm trying to write a program that takes an int
parameter and print a word of length n
that consists of both letters 'a' and 'b' for example: 我正在尝试编写一个带有int
参数的程序,并输出一个长度为n
的单词,该单词由字母“ a”和“ b”组成,例如:
n= 3
the result =>: `aaa,baa,aba,aab,bba,bab,abb,bbb`
And this is my code. 这是我的代码。 There is something wrong in it: 里面有问题:
#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;
}
can someone help me please ??? 有人能帮助我吗 ???
Just do char word[n] = "aaaaa";
只是做char word[n] = "aaaaa";
Full code: 完整代码:
#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;
}
Of course this work when you know the length of your words at compile time. 当然,当您在编译时知道单词的长度时,这项工作就可以了。 It the length would be known only at runtime (for example with a user inputting it) you need do dynamically allocate (with malloc
for example) and remove. 该长度仅在运行时才知道(例如,在用户输入时),您需要动态分配(例如,使用malloc
)并删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.