[英]how to replace character in string
int main(){
char* str = "bake", *temp = str;
char alpha [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for (int i = 0 ; temp[i] != '\0'; i++) {
for (int j = 0; alpha[j] != '\0'; j++) {
temp[i] = alpha[j];
printf("%s\n",temp);
}
temp = str;
}
return 0;
}
為什么我要嘗試替換落在我身上的特定位置的角色? 我希望它像那樣打印我
i = 0 (index 0 he change only the first char).
aake
bake
cake
dake
....
i = 1(index 1 he change only the second char).
bake
bbke
bcke
bdke
....
我不明白為什么temp[i] = alpha[j]
不起作用...我需要做什么才能更改字符。 非常感謝你的幫助
:[在此處輸入圖片描述][1] [1]: https.//i.stack.imgur.com/v0onF.jpg
正如評論中所說,您的代碼中有幾個錯誤。 首先,正如bruno所說,您不能修改文字字符串。 其次,當您編寫 *temp=str 時,您是在說“指針 temp 現在指向與 str 相同的地址”,簡而言之,這樣做,如果您修改 temp 中的數組,您也會修改 str 中的數組,並且反之亦然,因為它們是相同的。
下面你有一個可能的解決方案,使用 malloc 在 temp 和 strcpy 創建一個新數組,以便在每個外部循環后將 str 復制到 temp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char str[]= "bake",*temp;
temp=malloc((strlen(str)+1)*sizeof(char));
strcpy(temp,str);
char alpha [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for (int i = 0 ; temp[i] != '\0'; i++) {
for (int j = 0; alpha[j] != '\0'; j++) {
temp[i] = alpha[j];
printf("%s\n",temp);
}
strcpy(temp,str);
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.