如何替换字符串中的字符
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] != '[=10=]'; i++) {
for (int j = 0; alpha[j] != '[=10=]'; 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] != '[=10=]'; i++) {
for (int j = 0; alpha[j] != '[=10=]'; j++) {
temp[i] = alpha[j];
printf("%s\n",temp);
}
strcpy(temp,str);
}
return 0;
}
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] != '[=10=]'; i++) {
for (int j = 0; alpha[j] != '[=10=]'; 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] != '[=10=]'; i++) {
for (int j = 0; alpha[j] != '[=10=]'; j++) {
temp[i] = alpha[j];
printf("%s\n",temp);
}
strcpy(temp,str);
}
return 0;
}