0

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.

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

5 Comments

If your system has memmove there is no need for two copies. Generalizing to the case where the substring to be removed may occur more than once is a fun exercise.
Why not just use memmove(sentence + wordStart, sentence + wordEnd, stringLength - wordEnd)?
Because i need to show "what I have deleted"... I have solved this, will try this with memmove now :) ty
Actually what i need is to delete word by enetered number. and when i wish to delete 1st word from a sentence with 1 word - it failed... trying to solve this.
@dmckee: memmove ist C standard (C89), every 'pure C' system must support this
2

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.