Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 645
jergason Avatar asked Nov 30 '22 19:11

jergason


2 Answers

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.

like image 146
Chris Lutz Avatar answered Dec 18 '22 08:12

Chris Lutz


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!

like image 24
hhafez Avatar answered Dec 18 '22 09:12

hhafez