December 21, 2011

Converting a space delimited sentence into a sequence of null terminated strings

The title says it all, you are given a string which consists of words separated by spaces, here is a snippet of code for converting the same into a sequence of null terminated strings and then later printing them. Returning the indices in the original string where the words begin is the key here :




Printing the strings is pretty trivial as :




Quick code, picked up the hack from a certain shell command parsing code in Xinu.

2 comments:

  1. Nice. But this is where C astounds me with its verbosity. One reasons why I prefer powerful languages like python, groovy or smalltalk.

    For example: The same program in groovy would be a one liner, something like this

    println yourString.tokenize(' ').join(null)

    ReplyDelete
  2. totally agree, it would be equally simple in python. But for example, when you are writing the shell parsing code in an operating system like Xinu for the kernel, all you have is the bare minimal C support :)

    ReplyDelete