-
strings
Hello everyone. I'm looking to expand my knowledge about strings but I am stuck on a particular problem... I am hoping that by writing it down and trying to explain my problem I might be able to think of a solution or get hints on how to solve it.
I want to be able to search through a string for a particular character and insert a word inside.
So for example I have the string "dog" and would like to replace the character "o" with the string "cat".
So the output with be dcatg.
This is what I have so far
but it doesn't work
Code:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
char str1[15] = "dog";
char str2[15] = "cat";
int i;
char temp[15];
for(i=0;i<3;i++){
if(str1[i]="o"){
for(j=i;j<3;j++){
temp[j]=str1[j];
}
strcmp(str1[i], str2);
for(j=i;j<3;j++){
str1[j]=temp[j];
}
}
}
return 0;
}
-
Ok, it's probably a good idea that you get more familiar with the string library (#include string.h) and maybe learn a little more about pointers.
Basically what you have to do is locate the desired character an o in this case... take a look at what strchr() does for you.
Once you find it you need to copy out the rest of the string to a temp buffer, which I see you've already made ... look at strcpy() for this
Then you need to inject your new text overwriting all or some of the tail part... again strcpy() does a good job
Finally you need to concactenate (add) the tail back onto your string...
Code:
void InjectString(char *dst, char key, char *new)
{ char *ptr; // pointer for string manipulation
char temp[16]; // temp buffer for injection
ptr = strchr(dst,key); // find key character
strcpy(temp, ptr); // copy the tail skipping the key
strcpy(ptr,new); // inject the new text at ptr
strcat(dst,temp); } // put the tail back.
You would call this as... InjectString("absolutely",'l',"freaking");
and you would get back absofreakinglutely...
This is why there is a standard C library, it makes tasks like this easy. Yes, you can do it with loops, but that's a lot of work... unless you are deliberately trying to learn about arrays and loops.