Help With String Manipulation In C

AI Thread Summary
The discussion centers on a homework assignment requiring the replacement of "cmpt" with "XXXX" in a string using C programming. The original attempt at a solution involved a loop checking for the substring and replacing characters individually, but it was deemed inelegant. A participant suggested using the `strstr` function to simplify the task, which aligns with the teacher's requirement to utilize string functions. The conversation highlights the balance between adhering to assignment constraints and finding efficient coding solutions. Ultimately, the use of built-in functions can often lead to cleaner and more effective code.
NDiggity
Messages
53
Reaction score
0

Homework Statement


I need to write a function which will replace any occurence 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.
 
Back
Top