如何使用标准库将字符串转换为大写?

Sve*_*tad -1 c

我试图使用for带有 ASCII 表的循环,通过用 32 减去字母数字来使字符串中的每个字符一一大写。但我不能i在 charstr和中使用 int str2。我怎样才能做到这一点?

#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define STRLEN 200

void string_lower() {

}

void string_upper(char str) {
    char str2;
    
    int length = strlen(str);
    for (int i = 0; i < length; i++) {
        str2[i] = str[i - 32];
    }
}

int main() {
    char word[STRLEN] = { 0 };
    char word1 = 97;

    printf("Write a word");
    fgets(word, STRLEN, stdin);

    string_upper(word);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

chq*_*lie 5

您可以使用toupper()一次将一个字符转为大写。这适用于单字节字符集(例如 ASCII),但不适用于当今非英语脚本普遍使用的 UTF-8 编码。

\n

这是修改后的版本:

\n
#include <ctype.h>\n#include <stdio.h>\n\n#define STRLEN 200\n\nchar *string_upper(char *str) {\n    for (size_t i = 0; str[i] != '\\0'; i++) {\n        str[i] = toupper((unsigned char)str[i]);\n    }\n    return str;\n}\n\nint main() {\n    char word[STRLEN];\n\n    printf("Enter a word: ");\n    if (fgets(word, STRLEN, stdin)) {\n        printf("%s", string_upper(word);\n    }\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

参数必须强制转换为,(unsigned char)str[i]因为str[i]具有类型char,并且tolower()像所有函数和宏一样, from<ctype.h>仅为 typeunsigned char和特殊负值的值定义EOF。正如char在某些平台上可能签名的那样,直接将其传递给tolower()会对负值(例如'\xc3\xa9'和 )产生未定义的行为'\xc3\xbf'产生未定义的行为。

\n