Jergason Jergason - 2 months ago 15
C Question

Remove extra white space from inside a C string?

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.

Answer

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.