我正在尝试将C-String转换为所有小写字母而不使用ctype.h中的tolower。 我的代码似乎不起作用:我收到运行时错误。我要做的是改变大写字母bij'a' - 'A'的ASCII值,据我所知,它应该将这些值转换为小写的值。
#include <stdio.h>
void to_lower(char* k) {
char * temp = k;
while(*temp != 0) {
if(*temp > 'A' && *temp < 'Z') {
*temp += ('a' - 'A');
}
temp++;
}
}
int main() {
char * s = "ThiS Is AN eXaMpLe";
to_lower(s);
printf("%s",s);
}
答案 0 :(得分:9)
两个错误。
此代码不会将A和Z转换为小写:
if(*temp > 'A' && *temp < 'Z') {
使用&gt; =和&lt; =代替。
尝试修改字符串文字是不合法的!数组可以修改,字符串文字不能修改。
将char * s = "ThiS Is AN eXaMpLe";
更改为char s[] = "ThiS Is AN eXaMpLe";
答案 1 :(得分:1)
即使您不使用现有的标准库函数,遵循其界面仍然有用。 tolower
转换个人角色。将此函数应用于字符串可以写为解耦函数。
#include <stdio.h>
#include <string.h>
int to_lower (int c) {
if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c))
c = c - 'A' + 'a';
return c;
}
void mapstring (char *str, int (*f)(int)) {
for (; *str; str++)
*str = f(*str);
}
int main() {
char s[] = "THIS IS MY STRING";
mapstring(s, to_lower);
printf("%s\n", s);
return 0;
}
答案 2 :(得分:0)
我可以立即看到两个问题:(1)char *s = "This..."
创建一个不可写的字符串。您需要使用字符数组并将字符串复制到其中。 (2)if (*temp > 'A' && *temp < 'Z')
跳过A和Z.您需要>=
和<=
。