[英]How do I use putchar to “squeeze” characters (Ansi-C)
我想知道是否可以为我的代码获得一些帮助。 我在下面放了一些部分代码
/*reads char by char til EOF*/
while((c = getchar()) != EOF)
{
if(c == '\t')
{
putchar(' ');
}
else if(c == ' ')
{
putchar('d');
}
else
{
putchar(c);
}
}
我现在要做的是挤压用户输入的空格字符。 因此,如果用户输入:
a[空间][空间][空间][空间][空间][空间][空间][空间]a
output 应该只是
a[空间]a
现在我已经设置它替换 d 的所有空格以用于测试目的。 我将如何更改我的代码,以便它只打印出 1 个空格而不是用户输入的所有空格。
感谢您提前提供任何帮助。
只需保留一个空格标志:
int lastWasSpace = 0;
while((c = getchar()) != EOF) {
if(c == '\t' || c == ' ') { // you could also use isspace()
if(!lastWasSpace) {
lastWasSpace = 1;
putchar(c);
}
} else {
lastWasSpace = 0;
}
}
一种解决方案:
/*reads char by char til EOF*/
int hasspace = 0;
while((c = getchar()) != EOF)
{
if (isspace(c))
hasspace = 1;
}
else
{
if (hasspace)
{
hasspace = 0;
putchar(' ');
}
putchar(c);
}
}
jcomeau@intrepid:/tmp$ cat compress.c; echo 'this is a test' | ./compress
#include <stdio.h>
int main() {
int c, lastchar = 'x';
while ((c = getchar()) != EOF) {
if (c == '\t' || c == ' ') {
if (lastchar != ' ') {
putchar(' ');
lastchar = ' ';
}
} else {
putchar(c);
lastchar = c;
}
}
}
this is a test
首先,您是如何声明c
?
while((c = getchar()) != EOF)
如果c
是char
,那么它不能包含所有字符和EOF
。 确保使用大于char
的数据类型声明c
(通常为int
)。
接下来,您可以使用一个便宜的技巧来处理压缩多个空格:
int space_seen = 0;
while((c = getchar()) != EOF)
{
if(c == '\t')
{
putchar(' ');
}
else if(c == ' ')
{
if (!space_seen)
{
putchar('d');
space_seen = 1;
}
}
else
{
putchar(c);
space_seen = 0;
}
}
这个技巧也适用于跟踪解析字符串。
记录打印空格的时间,在找到另一个字母之前不要再打印它们。
使用您的代码作为基础:
unsigned char space = 0;
/* reads char by char until EOF */
while((c = getchar()) != EOF)
{
if(c == '\t')
{
putchar(' ');
}
else if(c == ' ')
{
/* state specific action */
if(space == 0) {
putchar('d');
space = 1; /* state transition */
}
}
else
{
/* state transition */
if(space == 1) {
space = 0;
}
putchar(c);
}
}
那里有 go。 一个非常非常简单的 state 机器。 就这么简单!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.