[英]How to convert a string (char *) to upper or lower case in C
I have a struct: 我有一个结构:
typedef struct entry {
char *surname;
int house_no;
char *postcode;
} BEntry;
and a function to convert strings to upper case: 以及将字符串转换为大写的函数:
void toUpper(char *str){
while (*str != '\0')
{
*str = toupper(*str);
str++;
}
}
and in my main function I assign values to the struct members and want to convert the surname to upper case: 在我的main函数中,我将值赋给struct成员,并希望将姓氏转换为大写:
mentry->surname = "bob";
mentry->house_no = 17;
mentry->postcode = "GK116BY";
toUpper(me->surname);
What is the correct way to convert a string to upper case by passing a char pointer to a function like this? 通过将char指针传递给这样的函数,将字符串转换为大写的正确方法是什么? My program is returning a segmentation fault.
我的程序正在返回分段错误。 Any help is most appreciated, thanks.
非常感谢任何帮助,谢谢。
Your toUpper()
implementation should work fine. 你的
toUpper()
实现应该可以正常工作。 However, you should pay attention to the warnings from your compiler (or turn up the warning levels if you didn't get any -- you should see something when you assigne a string literal to a char *
like that). 但是,您应该注意编译器的警告(或者如果您没有得到任何警告级别,那么当您将字符串文字分配给类似的
char *
时,您应该看到一些内容)。 String literals are const
, ie they cannot be modified. 字符串文字是
const
,即它们不能被修改。 When you try to write to them, this will cause the segmentation fault you are seeing. 当您尝试写入它们时,这将导致您看到的分段错误。
You need something like: 你需要这样的东西:
mentry->surname = malloc(4);
strcpy(mentry->surname, "bob");
or the more convenient, but not part of the C standard way: 或者更方便,但不是C标准方式的一部分:
mentry->surname = strdup("bob");
And of course, be sure to call free()
later, either way. 当然,无论如何,请务必稍后调用
free()
。
String literals like "Hello, World!"
字符串文字,如
"Hello, World!"
are not writeable. 是不可写的。 Either duplicate the string literal:
复制字符串文字:
hw = strdup("Hello, World!");
or declare a char[]
variable and initialize it to a string literal. 或声明
char[]
变量并将其初始化为字符串文字。 As a special case, string literals used this way are writeable: 作为特例,使用这种方式的字符串文字是可写的:
char hw[] = "Hello, World!";
The easiest way of converting char *
to lowercase or uppercase in c, is by using strdup
在c中将
char *
转换为小写或大写的最简单方法是使用strdup
#include <string.h>
char *to_uppercase(char *s)
{
int i = 0;
char *str = strdup(s);
while (str[i])
{
if (str[i] >= 97 && str[i] <= 122)
str[i] -= 32;
i++;
}
return (str);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.