从C字符串中删除多余的空白? [英] Remove extra white space from inside a C string?
问题描述
我已阅读文本的几行到C-字符串数组。该行有标签或空格分隔栏的任意数,我试图找出如何删除它们之间的所有多余的空格。最终的目标是使用的strtok分手列。这是列的一个很好的例子:
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
另外,可我只是一个不同的字符全部替换列之间的空白,以使用strtok的?像这样的事情?
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.
推荐答案
如果可能我的声音你这样做是错误的的意见,为什么不只是消除了空白,而读?使用的fscanf(%S,字符串);
来读一个字(无空格),然后读取空白。如果它是空格或制表符,请继续阅读到一个数据线。如果它是一个新行,开始新的条目。这是在C最容易尽快将数据进入你能处理的格式,而不是试图做重型文本操作。
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.
这篇关于从C字符串中删除多余的空白?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!