帮助!我正在用C编写一个程序来获取所有的首字母 - 我对指针一无所知所以我们试着远离那些 - 这就是我到目前为止所做的:
#include <stdio.h>
//CS50 Library for 'get_string() user input'
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void){
printf("Enter your name: ");
//User input for string
string s = get_string();
int i = 0;
//Determine whether the first chars are space - if not print char
if(s[0] != isspace(s[0])){
printf("%c",s[0]);
}
//loop through each Char - determine char is not space
while(s[i] != '\0'){
if(s[i] == ' '){
//if i'th char is space - add one to it thus printing char that comes after space
printf("%c", toupper(s[i+1]));
}
//advance i'th char count
i++;
}
printf("\n");
}
当我输入&#34; John Gerald Smith&#34;该节目以&#34; JGB&#34;回来,但如果我尝试输入类似的东西:&#34;约翰杰拉德史密斯&#34;(多个空格),似乎没有删除任何空格。我仍然得到输出的首字母,但我需要确保它根本不打印任何空格。请帮忙!这是家庭作业,所以我不希望得到答案,但如果有人能给我一些关于如何做到这一点的信息我会非常感激。谢谢!
答案 0 :(得分:1)
我通过避免字符串中第一个字符的“特殊情况代码”来解决@yajiv的原始和答案。
我会在列表中运行一次并使用一些“状态”来知道何时输出一个字符。
当我们看到一个空格时,我们知道我们想要输出下一个非空格(所以我们设置printNextNonSpace
)
当我们看到非空格时,如果设置了printNextNonSpace
,我们会打印它(然后我们清除printNextNonSpace
以避免打印额外的字符)
printNextNonSpace
最初设置为1,因此我们打印字符串中的第一个字符(如果它不是空格)。
请注意,这将处理字符串"Andrew Bill Charlie" -> "ABC"
," David Edgar Frank " -> "DEF"
[代码删除,因为OP明智地希望提示不能在盘子上回答]
答案 1 :(得分:0)
#include <stdio.h>
//CS50 Library for 'get_string() user input'
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void){
printf("Enter your name: ");
//User input for string
string s = get_string();
int i = 0;
//Determine whether the first chars are space - if not print char
if(!isspace(s[0])){
printf("%c",s[0]);
}
i++;
//loop through each Char - determine char is not space
while(s[i] != '\0'){
if(s[i-1]==' ' && s[i] != ' '){
//if i'th char is space - add one to it thus printing char that comes after space
printf("%c", toupper(s[i]));
}
//advance i'th char count
i++;
}
printf("\n");
}
首先检查天气前一个字符是否为空格,如果是空格则检查当前字符是否为空格,如果不是空格则打印当前字符,否则不是。
希望这有帮助。