如何替换字符串中的字符

阿里尔·多姆奇克
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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章