Thread: strtok() and original string

  1. #1
    Registered User
    Join Date
    Jan 2016
    Posts
    43

    SOLVED: strtok() and original string

    I want to look at the problem of tokenizing a string. Calling strtok() changes the original string by placing '\0' in lieu of the tokens. I was wondering if there was a trick to avoid this. I want to leave the original string intact and preferably don't want to copy it either.

    Looking at this answer on SO, what does this poster mean??

    C strtok() split string into tokens but keep old data unaltered - Stack Overflow
    Last edited by wiqxlzxsxj; 10-13-2020 at 03:31 PM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Unfortunately, strtok works by modifying the source string, so if you want to use strtok, the only way to leave the original string intact is to copy it and then run strtok on the copy. The advantage of strtok doing this is that if you don't care for original string remaining intact, then by recording pointers to the tokens, you could save on having to allocate additional space for the tokens because they would occupy the same storage as the original string.

    Quote Originally Posted by wiqxlzxsxj
    Looking at this answer on SO, what does this poster mean??
    That's just telling you to make a copy of the string content itself rather than merely making a copy of a pointer to the string content.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2016
    Posts
    43
    Thank u

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting the last word from a string using strtok?
    By potatoes1 in forum C Programming
    Replies: 2
    Last Post: 05-13-2017, 02:08 AM
  2. comparing string to strtok
    By loloxx in forum C Programming
    Replies: 8
    Last Post: 03-23-2012, 06:18 PM
  3. Replies: 7
    Last Post: 03-17-2012, 09:36 PM
  4. Simple Removal of string in string via strtok.
    By Vincent Wouters in forum C Programming
    Replies: 6
    Last Post: 11-11-2011, 01:48 PM
  5. loop in the same string using strtok
    By vitvar in forum C Programming
    Replies: 5
    Last Post: 10-27-2009, 07:14 AM

Tags for this Thread