【发布时间】:2021-01-14 06:50:38
【问题描述】:
在制作字符串函数的过程中,我尝试构建一个类似于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;
^~~~~~~~~~~~~ ~~
如果 char 被认为是来自 A-Z 的字母,我想增加它的值。事实证明我不能,因为 char 在数组中,而且我这样做的方式似乎对计算机没有意义。
问:我可以使用哪些替代方法来完成此功能?您能否进一步解释为什么会出现此错误?
【问题讨论】:
-
你想把它转换成
int,增加它,然后把它塞回char吗?如果是这样:text[i] = (int) text[i] + x。请记住,这只是乞求看似奇怪的溢出错误,因为这两种表示方式截然不同。 -
为什么不只是
text[i] |= 32而忘记int转换? -
旁注: 如您所见,
hello指向 指向一个字符串常量 [可能已加载到 R/O 内存中]。要让它工作,请执行以下操作:char hello[] = "Hello, world!";现在,array 字符在堆栈上(即可修改)。 -
您可能会在此处遇到 未定义的行为,因为您正在尝试修改(通过指针)字符串文字的数据(其中编译器完全有权存储在只读代码段中)。
-
不要硬编码
32。如果你打算这样做,为了未来读者的理智,请写'a' - 'A'
标签: c char c-strings string-literals function-definition