在 C 中将 char * 转换为大写

Converting char * to Uppercase in C

我试图在 c 中将 char * 转换为大写,但函数 toupper() 在这里不起作用。

我正在尝试获取 temp 的值的名称,该名称可以是冒号之前的任何内容,在本例中是“Test”,然后我想将名称完全大写。

void func(char * temp) {
 // where temp is a char * containing the string "Test:Case1"
 char * name;

 name = strtok(temp,":");

 //convert it to uppercase

 name = toupper(name); //error here
 
}

我收到错误消息,函数 toupper() 需要一个 int,但收到一个 char *。问题是,我必须使用 char *s,因为这是函数正在接受的内容,(我真的不能在这里使用 char 数组,可以吗?)。

如有任何帮助,我们将不胜感激。

toupper() 转换单个 char.

简单地使用一个循环:

void func(char * temp) {
  char * name;
  name = strtok(temp,":");

  // Convert to upper case
  char *s = name;
  while (*s) {
    *s = toupper((unsigned char) *s);
    s++;
  }

}

详细信息:为所有 unsigned charEOF 定义了标准库函数 toupper(int)。由于 char 可能已签名,因此转换为 unsigned char.

一些 OS 支持执行此操作的函数调用:upstr() and strupr()

toupper() 一次作用于一个元素(int 参数,值范围与 unsigned char 或 EOF 相同)。

原型:

int toupper(int c);

您需要使用循环从 字符串 中一次提供一个元素。

toupper() 仅适用于单个字符。但是有 strupr() 这就是您想要的指向字符串的指针。

对于那些想要大写字符串 并将其存储在变量中 的人(这正是我在阅读这些答案时所寻找的)。

#include <stdio.h>  //<-- You need this to use printf.
#include <string.h>  //<-- You need this to use string and strlen() function.
#include <ctype.h>  //<-- You need this to use toupper() function.

int main(void)
{
    string s = "I want to cast this";  //<-- Or you can ask to the user for a string.

    unsigned long int s_len = strlen(s); //<-- getting the length of 's'.  

    //Defining an array of the same length as 's' to, temporarily, store the case change.
    char s_up[s_len]; 

    // Iterate over the source string (i.e. s) and cast the case changing.
    for (int a = 0; a < s_len; a++)
    {
        // Storing the change: Use the temp array while casting to uppercase.  
        s_up[a] = toupper(s[a]); 
    }

    // Assign the new array to your first variable name if you want to use the same as at the beginning
    s = s_up;

    printf("%s \n", s_up);  //<-- If you want to see the change made.
}

注意:如果要将字符串改为小写,请将 toupper(s[a]) 更改为 tolower(s[a])

这个小功能怎么样?它假定 ASCII 表示字符并修改字符串。

void to_upper(char* string)
{
    const char OFFSET = 'a' - 'A';
    while (*string)
    {
        *string = (*string >= 'a' && *string <= 'z') ? *string -= OFFSET : *string;
        string++;
    }
}