如何在C语言中将字符追加到字符串数组 [英] How to append characters to a string array in C
问题描述
我是C语言的新手,我正在尝试编写一个程序来检查字符串是否包含任何大写字母,如果包含,则将其打印出来.我使用 https://www.onlinegdb.com/online_c_compiler# 作为我的编译器(原因我现在无法访问我的个人计算机),经过测试运行后,结果是(我知道得到的ps不安全):
I'm very new to C and I'm trying to write a program that checks if a string contains any uppercase letters, and if it does, prints them out. I'm using https://www.onlinegdb.com/online_c_compiler# as my compiler (cause I don't have access to my personal computer right now) and after a test run, the results are (p.s. I know gets isn't safe):
main.c:16:5: warning: ‘gets’ is deprecated [-Wdeprecated-declarations]
/usr/include/stdio.h:638:14: note: declared here
main.c:(.text+0x26): warning: the `gets' function is dangerous and should not be used.
sTrInG
Contains Uppercase!
Uppercase Letters:0
...Program finished with exit code 0
Press ENTER to exit console.
在这种情况下,我希望输出如下:
In this case, I expect an output something like this:
Contains Uppercase!
Uppercase Letters: TIG
我的脚本:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char str[100];
gets(str);
int containsUpper = 0;
char upperLetters[100] = {0};
for (int i=0; i < strlen(str); i++) {
if (islower(str[i])) {
continue;
} else {
containsUpper = 1;
upperLetters[i] = str[i]; // is this the bad line?
}
}
if (containsUpper) {
printf("Contains Uppercase!\n");
printf("Uppercase Letters:");
printf("%zu\n", strlen(upperLetters)); // prints 0 so upperLetters is empty..?
for (int i=0; i < strlen(upperLetters); i++) {
printf("%c", upperLetters[i]);
}
} else {
printf("Does not contain Uppercase!");
}
return 0;
}
推荐答案
您希望循环为:
int i, j=0;
for (i=0; i < strlen(str); i++) {
if (isupper((unsigned char)str[i])) {
upperLetters[j++] = str[i];
}
}
upperLetters[j]= '\0';
containsUpper = (j>0);
即,保留高位字母数组的单独索引.并且不要忘记终止它.
That is, keep a separate index of the upper letters array. And don't forget to terminate it.
一种更好的循环方法是:
A better way for the loop is:
int i, j, k;
for (i=0, j=0, k=strlen(str); i < k; i++) {
,因为它只调用一次strlen
.
正如用户LxerLx所指出的,不是小写字母的字符不必是大写字母.我为此更新了循环.
As user LxerLx pointed out, a character which is not a lower case letter does not have to be an upper case letter. I updated the loop for this.
这篇关于如何在C语言中将字符追加到字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!