我对C很陌生,我正在努力打印字符串中每个单词的第一个字母。 我知道我打印第一个单词的第一个字母,之后我应该搜索空格,所以我知道下一个字符肯定是我要打印的下一个字母,但我不知道如何写出匹配代码。 我写的代码是垃圾,所以我没有发布。 我只需要一些提示来了解如何编写代码 谢谢!
答案 0 :(得分:0)
您可以尝试以下方式:
void print_first_letters(char *input)
{
// Check the argument validity.
if(input == NULL) return;
// Get the length of the input string.
int length = strlen(input);
// Print the very first character, if it is a valid one.
if(input[0] != ' ' && input[0] != '\0') printf("%c\n", input[0]);
// Loop over the string, character by character.
for(int i = 0; i < length; i++){
// Check if the current character is a whitespace.
if(input[i] == ' '){
// If there is a next character, and it is NOT a whitespace, print it!
if(i + 1 < length && input[i + 1] != ' '){
printf("%c\n", input[i + 1]);
}
}
}
}
您需要包含string.h才能使strlen()正常工作。或者,如果长度已知,则可以将输入的长度作为参数传递。