逐个字符处理字符串并计算空格(只要您聚合空格等)并没有错,但是,还有另一种方法可以考虑更多的灵活性。您可以使用strtok(在string.h)来标记您的输入字符串,而不是搜索空格。然后,只需计算 tokens(单词)并将添加的内容作为第 n 个单词(或单词)插入到适当的位置(索引)。
#include <stdio.h>
#include <string.h>
enum { MAXC = 512 };
int main (void) {
char *w1 = "one", *w2 = "two"; /* replacement words */
int nth1 = 3, nth2 = 4; /* positions for w1/w2 */
char line[MAXC] = "", *p = NULL, *delim = " \t.,;\n";
char *fmt1 = "%s", *fmt2 = " %s";
while (fgets (line, MAXC, stdin)) { /* for each line read from stdin */
int idx = 0; /* tokenize line with strtok */
for (p = strtok (line, delim); p; p = strtok (NULL, delim)) {
printf (!idx ? fmt1 : fmt2, p); idx++; /* print token */
if (idx == nth1) printf (fmt2, w1); /* check and insert w1 */
if (idx == nth2) printf (fmt2, w2); /* and w2 in nth pos */
}
putchar ('\n');
}
return 0;
}
(注意:您可以根据需要定制索引。例如,您可以在插入第 nth 个单词后增加索引 idx 以让它们按顺序插入等...)
使用/输出示例
$ echo "Simple sentence containing some random words" | ./bin/replacenthword
Simple sentence containing one some two random words
由于您没有对要操作的字符串进行硬编码,因此您现在可以在发送它的任何行中替换 nth1 或 nth2 单词,如果您在整个文件中比如,例如
输入文件示例
$ cat dat/replcmt.txt
Simple sentence containing some random words
A quick brown fox jumps over the lazy dog
Fewer words
That's all folks
示例使用/输出带文件
$ ./bin/replacenthword <dat/replcmt.txt
Simple sentence containing one some two random words
A quick brown one fox two jumps over the lazy dog
Fewer words
That's all folks one
如果你只想插入第nth个单词如果有后面的单词,那么你需要做的就是改变每个token的测试和打印顺序。
while (fgets (line, MAXC, stdin)) { /* for each line read from stdin */
int idx = 0; /* tokenize line with strtok */
for (p = strtok (line, delim); p; p = strtok (NULL, delim)) {
if (idx == nth1) printf (fmt2, w1); /* check and insert w1 */
if (idx == nth2) printf (fmt2, w2); /* and w2 in nth pos */
printf (!idx ? fmt1 : fmt2, p); idx++; /* print token */
}
putchar ('\n');
}
这将产生相同的输出,但如果行中出现nth1 或更少的标记(单词),则省略替换,例如
$ ./bin/replacenthword <dat/replcmt.txt
...
That's all folks
查看所有答案,如果您有任何问题,请告诉我。