If you know the string is big enough to hold all of the extra characters, it's a relatively simple matter of finding instances of "LTD", shifting everything after the matched substring (to make room), and copying the new substring in:
#include <stdio.h>
#include <string.h>
int main ( void )
{
char company[50] = "STEPHEN JOHNSON LTD";
char *match = strstr ( company, "LTD" );
if ( match != NULL ) {
memmove ( match + 7, match + 3, strlen ( match + 3 ) );
memcpy ( match, "LIMITED", 7 );
puts ( company );
}
return 0;
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>Does that make sense?
Absolutely. Unfortunately there's not a standard strrstr function, so the most straightforward solution is to save the previous match until strstr fails. At that point you know you've got the last instance of the substring:
#include <stdio.h>
#include <string.h>
int main ( void )
{
char company[50] = "LTD STEPHEN LTD JOHNSON LTD";
char *match = company;
char *last = NULL;
while ( ( match = strstr ( match, "LTD" ) ) != NULL ) {
last = match;
match += 3; /* Skip the match so we don't loop forever */
}
if ( last != NULL ) {
memmove ( last + 7, last + 3, strlen ( last + 3 ) );
memcpy ( last, "LIMITED", 7 );
puts ( company );
}
return 0;
}
Of course, that might not be a perfect solution if by "not the end" you mean the last word in the string. In that case both the test and replacement are conceptually easier, especially if you don't care about trailing whitespace:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main ( void )
{
char company[50] = "LTD STEPHEN LTD JOHNSON LTD";
size_t i = strlen ( company );
do
--i;
while ( isspace ( company[i] ) );
if ( i >= 2 && strncmp ( &company[i - 2], "LTD", 3 ) == 0 )
strcpy ( &company[i - 2], "LIMITED" );
puts ( company );
return 0;
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401