如何将 tolower() 与 char* 一起使用?

Poo*_*mer 3 c char tolower

我有一个包含一些单词的 .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;
}
Run Code Online (Sandbox Code Playgroud)

例子:

你好.txt

Foo;
Bar.
Baz.
Run Code Online (Sandbox Code Playgroud)

预期产出

foo
bar
baz
Run Code Online (Sandbox Code Playgroud)

cha*_*had 5

tolower函数接受单个字符并将其变为小写,因此在 a 上调​​用它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, ",.; "); 
}
Run Code Online (Sandbox Code Playgroud)

如果字符串中有更多可能是大写的字符,并且您想确保它们变为小写,则需要迭代子字符串并调用tolower每个字符:

while(ptr != NULL)  
{
    for (char *ch = ptr; *ch; ch++)
    {
        *ch = tolower((unsigned char) *ch);
    }
    words[i]= ptr;
    i++;
    ptr = strtok(NULL, ",.; "); 
}
Run Code Online (Sandbox Code Playgroud)

  • `tolower()` 接受 `unsigned char` 或 `EOF` 范围内的 `int`。健壮的代码使用 `*ch = tolower((unsigned char) *ch);` 来避免 UB。 (7认同)