所以我需要将字符串变为大写并从中删除空格。然而它不起作用,如果字符串包含数字,最终打印会打印一些非 ASCII 字符。我应该如何让它发挥作用?我尝试使用函数 isalpha()
和 isdigit()
来完成此操作,但结果是相同的。
#include <stdio.h>
#include <ctype.h>
int main(){
int i = 0;
char c[100];
char str[] = "Hello8 world";
while(str[i]){
if (str[i]!=' '){
if (str[i] >= '0' && str[i] <= '9'){
c[i]=str[i];
}
else{
c[i]=(toupper(str[i]));
}
i++;
}
}
printf("%s", c);
return(0);
}
最佳答案
这里有几处错误。首先,您只在 if
语句内推进 i
,因此一旦遇到空格,您的问题就会陷入 endlees 循环。
其次,您假设源字符串和目标字符串中的索引相同 - 这是不正确的,因为您正在跳过空格。这将导致目标字符串保留未初始化的内存 - 在某些平台上可能是 \0
,而在其他平台上可能只是随机垃圾。相反,您应该维护两个索引计数器,一个用于源,一个用于目标,并在完成后在目标末尾显式设置 \0
:
int i = 0;
int j = 0; /* Target string index */
char c[100];
char str[] = "Hello8 world";
while(str[i]){
if (str[i]!=' '){
if (str[i] >= '0' && str[i] <= '9'){
c[i]=str[i];
}
else{
c[j]=(toupper(str[i]));
}
j++; /* Target index advance only when it's used */
}
i++; /* Source index advanced regardless */
}
c[j] = '\0'; /* Handle the string termination */
printf("%s\n", c);
关于c - 如果包含数字,如何使整个字符串大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40318697/