将 C 字符串转换为全低
Converting a C-String to all lower
我试图在不使用 ctype.h 中的 tolower 的情况下将 C 字符串转换为所有小写。
但是我的代码似乎不起作用:我收到运行时错误。我想做的是改变大写字母 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);
}
两个错误。
此代码不会将 A 和 Z 转换为小写:
if(*temp > 'A' && *temp < 'Z') {
改用 >= 和 <=。
并且尝试修改字符串文字是不合法的!数组可以修改,字符串文字不能。
将 char * s = "ThiS Is AN eXaMpLe";
更改为 char s[] = "ThiS Is AN eXaMpLe";
我可以立即看到两个问题:(1) char *s = "This..."
创建了一个不可写的字符串。您需要使用字符数组并将字符串复制到其中。 (2) if (*temp > 'A' && *temp < 'Z')
跳过 A 和 Z。您需要 >=
和 <=
。
即使你不使用现有的标准库函数,遵循它的接口可能还是有用的。 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;
}
我试图在不使用 ctype.h 中的 tolower 的情况下将 C 字符串转换为所有小写。 但是我的代码似乎不起作用:我收到运行时错误。我想做的是改变大写字母 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);
}
两个错误。
此代码不会将 A 和 Z 转换为小写:
if(*temp > 'A' && *temp < 'Z') {
改用 >= 和 <=。
并且尝试修改字符串文字是不合法的!数组可以修改,字符串文字不能。
将 char * s = "ThiS Is AN eXaMpLe";
更改为 char s[] = "ThiS Is AN eXaMpLe";
我可以立即看到两个问题:(1) char *s = "This..."
创建了一个不可写的字符串。您需要使用字符数组并将字符串复制到其中。 (2) if (*temp > 'A' && *temp < 'Z')
跳过 A 和 Z。您需要 >=
和 <=
。
即使你不使用现有的标准库函数,遵循它的接口可能还是有用的。 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;
}