问题描述
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;
}
为什么我要替换掉落在我身上的特定位置的字符?我希望它能像这样打印我
Why am I trying to replace a character in a particular location it falls to me?i want it print me like that
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]
不起作用...我需要做的是我可以更改字符.非常感谢您的帮助
i don't understand why temp[i] = alpha[j]
not work... what i need to do that i can change the char.thank you a lot for helps
![在此处输入图片描述] [1][1]:https://i.stack.imgur.com/v0onF.jpg
![enter image description here][1][1]: https://i.stack.imgur.com/v0onF.jpg
推荐答案
如注释中所述,您的代码中存在几个错误.首先,如 bruno 所述,您不能修改文字字符串.其次,当您编写* temp = str时,您说的是指针temp现在指向与str相同的地址",简而言之,这样做的话,如果您在temp中修改数组,那么您也将在str中修改数组,反之亦然,因为它们相同.
As said in the comments, there are a couple of mistakes in your code. First of all, as stated by bruno you cannot modify a literal string. Secondly, when you write *temp=str you are saying "the pointer temp now points to the same adress as str", in short, doing this, if you modify the array in temp you will modify the array in str as well, and vice-versa, because they are the same.
下面有一个可能的解决方案,使用malloc在temp中创建一个新数组,并在每个外部周期之后使用strcpy将str复制到temp
Below you have a possible solution using malloc to create a new array in temp and strcpy to copy str to temp after each outter cycle
#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;
}
这篇关于如何替换字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!