Roni Jack Vituli
Roni Jack Vituli

Reputation: 192

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;
}

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
    ....

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

![enter image description here][1] [1]: https://i.sstatic.net/v0onF.jpg

Upvotes: 2

Views: 105

Answers (1)

fuscati
fuscati

Reputation: 101

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.

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;
}

Upvotes: 1

Related Questions