Hello

I was wondering whether someone could help me with the below

I have a variable called:

char company[50];

I have a string which contains:

"STEPHEN JOHNSON LTD"

I want to change the LTD to LIMITED

How do i do this?

Recommended Answers

All 3 Replies

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

Ha, fantastic Narue...

One more thing. I dont want to change the ltd if its not the end

eg

If i Had

Ltd Stephen Johnson Ltd

I would change this to Ltd Stephen Johnson Limited

Does that make sense?

>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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.