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