Cut out section of string

15,984

Solution 1

Use memmove to move the tail, then put '\0' at the new end position. Be careful not to use memcpy - its behaviour is undefined in this situation since source and destination usually overlap.

Solution 2

You can just tell printf to cut the interesting parts out for you:

char *string = "This is a string";
printf("%.*s%s", 4, string, &string[7]); // 'This a string'

:-)

Solution 3

If you're talking about getting rid of the middle of the string and moving the rest earlier in place, then I don't think there's a standard library function for it.

The best approach would be to find the end of the string, and then do an O(cut_size) cycle of shifting all the characters to the new location. In fact, there's a similar common interview question.

You have to be careful about using things like memory copy since the destination buffer overlaps with the source.

Share:
15,984
Tyler
Author by

Tyler

http://hackernewsers.com/users/tkahn6.html

Updated on June 25, 2022

Comments

  • Tyler
    Tyler almost 2 years

    I wouldn't mind writing my own function to do this but I was wondering if there existed one in the string.h or if there was a standard way to do this.

    char *string = "This is a string";
    
    strcut(string, 4, 7);
    
    printf("%s", string); // 'This a string'
    

    Thanks!

  • Uri
    Uri about 15 years
    I think he wants to eliminate parts of the middle of the string and move the rest to an earlier offset.
  • Suroot
    Suroot about 15 years
    Sorry for missing that, seemed like you just wanted to print out a substring.
  • qrdl
    qrdl about 15 years
    Just allow memmove() to move extra byte with 0-terminator
  • TofuBeer
    TofuBeer about 15 years
    ... and then sprintf it into a new variable :-)