divide by zero
divide by zero

Reputation: 2370

Cut substring from a String in C

I have a string (ex. "one two three four"). I know that I need to cut word that starts from 4th to 6th symbol. How can I achieve this?

Result should be:

Cut string is "two"
Result string is "one three four"

For now I achieved, that I can get the deleted word - '

for(i = 0; i < stringLength; ++i) { 
          if((i>=wordStart) && (i<=wordEnd))
          {
              deletedWord[j] = sentence[i];
              deletedWord[j+1] = '\0';
              j++;                
          }
    }

but when I fill the sentence[i] = '\0' I have problems with cutting string in the middle.

Upvotes: 0

Views: 10898

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409136

Instead of putting '\0' in the middle of the string (which actually terminates the string), copy everything but the word to a temporary string, then copy the temporary string back to the original string overwriting it.

char temp[64] = { '\0' };  /* Adjust the length as needed */

memcpy(temp, sentence, wordStart);
memcpy(temp + wordStart, sentence + wordEnd, stringLength - wordEnd);
strcpy(sentence, temp);

Edit: With memmove (as suggested) you only need one call actually:

/* +1 at end to copy the terminating '\0' */
memmove(sentence + wordStart, sentence + wordEnd, stringLengt - wordEnd + 1);

Upvotes: 2

vrk001
vrk001

Reputation: 335

/*sample initialization*/
char sentence[100] = "one two three four";

char deleted_word[100];
char cut_offset = 4;
int cut_len = 3;

/* actual code */
if ( cut_offset < strlen(sentence) && cut_offset + cut_len <= strlen(sentence) )
{
    strncpy( deleted_word, sentence+cut_offset, cut_len);
    deleted_word[cut_len]=0;

    strcpy( sentence + cut_offset, sentence + cut_offset + cut_len);
}

Upvotes: 0

Christoffer
Christoffer

Reputation: 12910

When you set a character to '\0' you're terminating the string.

What you want to do is either create a completely new string with the required data, or, if you know precisely where the string comes from and how it's used later, overwrite the cut word with the rest of the string.

Upvotes: 2

Related Questions