[英]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.