您可以将x 赋予这样的函数。为了便于理解,第一个简单版本:
// header needed for isalpha()
#include <ctype.h>
void condense_alpha_str(char *str) {
int source = 0; // index of copy source
int dest = 0; // index of copy destination
// loop until original end of str reached
while (str[source] != '\0') {
if (isalpha(str[source])) {
// keep only chars matching isalpha()
str[dest] = str[source];
++dest;
}
++source; // advance source always, wether char was copied or not
}
str[dest] = '\0'; // add new terminating 0 byte, in case string got shorter
}
它将就地遍历字符串,复制匹配isalpha() 测试的字符,跳过并删除不匹配的字符。要理解代码,重要的是要意识到 C 字符串只是 char 数组,字节值 0 标记字符串的结尾。另一个重要的细节是,在 C 中,数组和指针在许多(不是全部!)方面都是相同的,所以指针可以像数组一样被索引。此外,这个简单的版本将重写字符串中的每个字节,即使字符串实际上没有改变。
然后是一个更全功能的版本,它使用作为参数传递的过滤函数,并且只会在 str 发生变化时进行内存写入,并像大多数库字符串函数一样返回指向 str 的指针:
char *condense_str(char *str, int (*filter)(int)) {
int source = 0; // index of character to copy
// optimization: skip initial matching chars
while (filter(str[source])) {
++source;
}
// source is now index if first non-matching char or end-of-string
// optimization: only do condense loop if not at end of str yet
if (str[source]) { // '\0' is same as false in C
// start condensing the string from first non-matching char
int dest = source; // index of copy destination
do {
if (filter(str[source])) {
// keep only chars matching given filter function
str[dest] = str[source];
++dest;
}
++source; // advance source always, wether char was copied or not
} while (str[source]);
str[dest] = '\0'; // add terminating 0 byte to match condenced string
}
// follow convention of strcpy, strcat etc, and return the string
return str;
}
过滤函数示例:
int isNotAlpha(char ch) {
return !isalpha(ch);
}
示例调用:
char sample[] = "1234abc";
condense_str(sample, isalpha); // use a library function from ctype.h
// note: return value ignored, it's just convenience not needed here
// sample is now "abc"
condense_str(sample, isNotAlpha); // use custom function
// sample is now "", empty
// fscanf code from question, with buffer overrun prevention
char x[100];
while (fscanf(inputFile, "%99s", x) == 1) {
condense_str(x, isalpha); // x modified in-place
...
}
参考:
阅读int isalpha ( int c );手册:
检查 c 是否为字母。
返回值:
如果 c 确实是一个字母,则该值不同于零(即 true)。否则为零(即假)