[英]Converting a variable length c-string to Fortran string in Visual Studio
[英]Converting a C-String to all lower
我正在尝试将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);
}
两个错误。
这段代码不会将A和Z转换为小写:
if(*temp > 'A' && *temp < 'Z') {
使用> =和<=代替。
并且尝试修改字符串文字是不合法的! 数组可以修改,字符串文字不能修改。
更改该char * s = "ThiS Is AN eXaMpLe";
到char s[] = "ThiS Is AN eXaMpLe";
即使您不使用现有的标准库功能,遵循其接口仍然可能很有用。 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;
}
我可以立即看到两个问题:(1) char *s = "This..."
创建了一个不可写的字符串。 您需要使用字符数组并将字符串复制到其中。 (2) if (*temp > 'A' && *temp < 'Z')
跳过A和Z。您需要>=
和<=
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.