在制作字符串函数的过程中,我尝试在类似于 strlwr()
的地方构建一个函数,我将其命名为 lowercase()
:
#include <stdio.h>
#include <ctype.h>
char *lowercase(char *text);
int main() {
char *hello = "Hello, world!";
printf("%s\n", lowercase(hello));
}
char *lowercase(char *text) {
for (int i = 0; ; i++) {
if (isalpha(text[i])) {
(int) text[i] += ('a' - 'A');
continue;
} else if (text[i] == '\0') {
break;
}
}
return text;
}
我了解到大字母和小字母的间距是32,这就是我使用的。但后来我得到了这个错误:
lowercase.c:14:13: error: assignment to cast is illegal, lvalue casts are not supported
(int) text[i] += 32;
^~~~~~~~~~~~~ ~~
如果字符被视为 A-Z 的字母,我想增加该字符的值。事实证明我不能,因为字符位于数组中,而我这样做的方式对计算机来说似乎没有意义。
问:我可以使用哪些替代方法来完成此功能?您能进一步解释一下为什么会出现这样的错误吗?
最佳答案
尽管在 C 字符串文字中具有非常量字符数组类型,但您不能更改字符串文字。
char *hello = "Hello, world!";
来自 C 标准(6.4.5 字符串文字)
7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
所以你应该像字符数组一样声明标识符hello
char hello[] = "Hello, world!";
在函数中,您不应使用 32
等魔数(Magic Number)。例如,如果编译器使用 EBCDIC 编码,您的函数将产生错误的结果。
在循环中,您必须使用 size_t
类型而不是 int
类型,因为 int 类型的对象可能无法存储该类型的所有值size_t
是 sizeof
运算符或函数 strlen
的返回类型。
本声明
(int) text[i] += 32;
没有意义,因为在表达式的左侧由于转换而存在右值。
该功能可以通过以下方式实现
char * lowercase( char *text )
{
for ( char *p = text; *p; ++p )
{
if ( isalpha( ( unsigned char )*p ) )
{
*p = tolower( ( unsigned char )*p );
}
}
return text;
}
关于c - 让 char 的 int 值递增的另一种方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64106398/