简体   繁体   中英

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.

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

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.

/*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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM