EDE*_*EDE 3 c string pointers strtok
我试图char *在c中将a 转换为大写,但该函数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
}
Run Code Online (Sandbox Code Playgroud)
我收到函数toupper期望int的错误,但收到一个char*.事实是,我必须使用char*,因为这是函数所采用的,(我不能在这里使用char数组,可以吗?).
任何帮助将不胜感激.
chu*_*ica 11
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++;
}
}
Run Code Online (Sandbox Code Playgroud)
细节:标准库函数toupper(int)是为所有unsigned char和EOF.既然char可以签名,转换为unsigned char.
一些操作系统支持执行此操作的函数调用:upstr()和strupr()
Mik*_*ike 10
对于那些想要将字符串大写并将其存储在变量中的人(这就是我在阅读这些答案时所寻找的)。
#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.
}
Run Code Online (Sandbox Code Playgroud)
注意:如果您想将字符串改为小写,请更改toupper(s[a])为tolower(s[a])。
toupper()仅适用于单个字符。但是strupr()对于指向字符串的指针,您需要的是什么。
小智 5
这个小功能怎么样?它假定 ASCII 表示的字符并就地修改字符串。
void to_upper(char* string)
{
const char OFFSET = 'a' - 'A';
while (*string)
{
*string = (*string >= 'a' && *string <= 'z') ? *string -= OFFSET : *string;
string++;
}
}
Run Code Online (Sandbox Code Playgroud)