我有一个包含一些单词的 .txt 文件,我需要它们是小写的。 如何让每个单词小写?仅将 tolower() 添加到 strtok() 是行不通的。我应该添加什么?或者首先对整个文件使用 tolower() 会更容易吗?但是怎么办?请帮忙!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <ctype.h>
int main(void)
{
char str[5000];
char *ptr;
char *words[5000];
FILE * fp = fopen("hi.txt", "r");
fgets(str, 49, fp);
ptr = strtok(str, ",.; ");
int i = 0;
while(ptr != NULL)
{
words[i]= ptr;
i++;
ptr = strtok(NULL, ",.; ");
}
fclose(fp);
for(int j=0;j<i;j++) {
printf("%s\n", words[j]);
//printf("%s\n", tolower(words[j])); // Doesn't work!
}
return 0;
}
例子:
你好.txt
Foo;
Bar.
Baz.
预期输出
foo
bar
baz
最佳答案
tolower
函数采用单个字符并将其变为小写,因此在 char*
上调用它实际上没有意义。如果您知道 strtok
返回的每个子字符串中只有第一个字符是大写,您需要在循环中专门针对该字符调用 tolower
。换句话说,像这样:
while(ptr != NULL)
{
ptr[0] = tolower((unsigned char) ptr[0]);
/*
Or equivalently ...
*ptr = tolower((unsigned char) *ptr)
*/
words[i]= ptr;
i++;
ptr = strtok(NULL, ",.; ");
}
如果字符串中有更多可能是大写的字符,而您想确保它们变成小写,则需要遍历子字符串并对每个字符调用 tolower
:
while(ptr != NULL)
{
for (char *ch = ptr; *ch; ch++)
{
*ch = tolower((unsigned char) *ch);
}
words[i]= ptr;
i++;
ptr = strtok(NULL, ",.; ");
}
关于c - 如何将 tolower() 与 char* 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41148978/