在我的主要功能中,我使用了 letter(ch)
。我试图让一些字母字符成为字符串或标记。在使用 append
函数之前,它只会打印出所有字符。
//output
000: u
001: s
002: e
003: .
004: s
005: y
006: s
007: t
008: e
009: m
010: .
011: i
012: o
013: ;
我找到了一个追加函数,它可以将字母字符放入数组中,但它打印出来的结果却像一个金字塔。如何在完成附加后得到最后的结果,并使用 '\0'
拆分它?它不应该已经被 append
函数中的初始 '\0'
拆分了吗?我在朝着正确的方向前进吗?为了在 null 之后进行拆分,我是否遗漏了什么?
//output
000: u
001: us
002: use
003: .
004: uses
005: usesy
006: usesys
007: usesyst
008: usesyste
009: usesystem
010: .
011: usesystemi
012: usesystemio
013: ;
//main.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include "ch_type.h"
FILE *file;
char line[400];
int line_num;
char ch;
void append(char* line, char ch)
{
int length = strlen(line);
line[length] = ch;
line[length + 1] = '\0';
}
int main()
{
file = fopen("source.txt", "r");
while((ch = fgetc(file)) != EOF)
{
if(space(ch))
{
printf(" %03d: %c\n", line_num++, ch);
}
if(letter(ch))
{
append(line, ch);
printf(" %03d: %s\n", line_num++, line);
}
if(separator(ch))
{
printf(" %03d: %c\n", line_num++, ch);
}
}
return 0;
}
//ch_type.h
int space(int ch)
{
return ((ch == ' '));
}
int letter(int ch)
{
return (((ch >= 'a') && (ch <= 'z')) || (ch >= 'A') && (ch <= 'Z'));
}
int separator(int ch)
{
return ((ch == '#') || (ch == '(') || (ch == ')') || (ch == '{') || (ch == '}') || (ch == '[') || (ch == ']')
|| (ch == '<') || (ch == '>') || (ch == '.') || (ch == ',') || (ch == ':') || (ch == ';'));
}
最佳答案
在输入 if(space(ch))
或 if(separator(ch))
时打印 line
而不是在找到每个字符后打印的一条线。之后,将第一个字节设置为 0
因此字符串再次为“空”:
if(space(ch))
{
printf(" %03d: %s\n", line_num++, line);
line[0] = '\0';
printf(" %03d: %c\n", line_num++, ch);
}
if(letter(ch))
{
append(line, ch);
}
if(separator(ch))
{
printf(" %03d: %s\n", line_num++, line);
line[0] = '\0';
printf(" %03d: %c\n", line_num++, ch);
}
您可能还应该将 else
添加到 if(letter(ch))
和 if(separator(ch))
之前。这可能会稍微提高性能,因为这些条件都不重叠。
请注意,这是假设分隔符和空格不在一起,但这不一定很重要。
这是一个不需要重复代码的简化版本:
if(letter(ch))
{
append(line, ch);
}
else
{
printf(" %03d: %s\n", line_num++, line);
line[0] = '\0';
}
if(space(ch) || separator(ch))
{
printf(" %03d: %c\n", line_num++, ch);
}
关于c - 如何将一个字符追加到数组中并将其标记化 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58313521/