Help With String Manipulation In C

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 9K views
NDiggity
Messages
53
Reaction score
0

Homework Statement


I need to write a function which will replace any occurrence of "cmpt" with "XXXX" in a string.

The Attempt at a Solution


I am still confused with pointers and string manipulations. Here is what I have so far but I'm lost.

http://rafb.net/p/2h8fJ210.html
 
Last edited by a moderator:
Physics news on Phys.org
You don't have to use pointers!

char string[] = "belgiumcmptbelgium";
for (int i=0;i<strlen(string)-4;i++) {
if ( 'c'==string && 'm'==string[i+1] && 'p'==string[i+2] && 't'==string[i+3] ) {
string='X';
string[i+1]='X';
string[i+2]='X';
string[i+4]='X';
break;
}
}

Not exactly elegent - but you get the point!
 
Ok, I figured out my problem and I still was able to use the strstr function because our teacher wants us to use one of the string functions. Thanks for the idea, i incorporated it. Sometimes the simplest way is the best! Thanks.
 
Last edited:
I was going to be sarcastic and suggest just use the strstr() function !
But i assumed this was one of those stupid homework/interview questions where you aren;t allowed to just use the real solution.