I have read a few lines of text into an array of C-strings. The lines have an arbitrary number of tab or space-delimited columns, and I am trying to figure out how to remove all the extra whitespace between them. The end goal is to use strtok to break up the columns. This is a good example of the columns:
Cartwright Wendy 93 Williamson Mark 81 Thompson Mark 100 Anderson John 76 Turner Dennis 56
How can I eliminate all but one of the spaces or tabs between the columns so the output looks like this?
Cartwright Wendy 93
Alternatively, can I just replace all of the whitespace between the columns with a different character in order to use strtok? Something like this?
Cartwright#Wendy#93
edit: Multiple great answers, but had to pick one. Thanks for the help all.
If I may voice the "you're doing it wrong" opinion, why not just eliminate the whitespace while reading? Use fscanf("%s", string);
to read a "word" (non whitespace), then read the whitespace. If it's spaces or tabs, keep reading into one "line" of data. If it's a newline, start a new entry. It's probably easiest in C to get the data into a format you can work with as soon as possible, rather than trying to do heavy-duty text manipulation.
Why not use strtok()
directly? No need to modify the input
All you need to do is repeat strtok()
until you get 3 non-space tokens and then you are done!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With