对于我正在做的作业,我必须从 C 字符串(或字符数组)中打印出首字母缩写。为此,我知道我需要找到空格在哪里,使用 (int)name[i] == 32 来查找当前字符是否是空格。我唯一的问题是我无法弄清楚如何找到空间,然后将下一个字符存储在字符数组中。 (例如,用户输入 Mike Baggins,我必须打印出 MB)。我将在下面发布我的代码,向您展示我已经走了多远。请帮忙,但请不要给我完整的解决方案。谢谢!
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
string name = get_string(); // gets the user's input
char firstI = name[0]; // stores the first character from the user's input
int len = strlen(name);
if((int)firstI >= 97 && (int)firstI <= 122) // checks if the character is lowercase
{
firstI -= 32; // makes the value uppercase
}
for(int i = 0; i < len; i++)
{
if((int)name[i] == 32) // checks if the character is SPACE
{
printf("I found a space!\n"); // prints out "I found a space"
}
}
printf("%c\n", firstI); // prints out the first initial
}
最佳答案
其实很简单,看这个例子
#include <stdio.h>
#include <ctype.h>
int
main(void)
{
char array[10];
char string[] = "Mike Baggins";
int j;
// Always put the first non-whitespace
// character (we should probably skip all
// spaces first
array[0] = string[0];
// Now start at the character following the first
j = 1;
for (int i = 1; ((string[i - 1] != '\0') && (j < sizeof(array) - 1)); ++i) {
if (string[i - 1] == ' ') {
array[j++] = toupper(string[i]);
}
}
array[j] = '\0';
puts(array);
return 0;
}
我所需要的只是知道字符串只是数组,带有一个特殊值标记它们的结尾 → '\0'
。当然,你可以改进它很多。例如,您可以计算输入字符串中有多少个缩写,并分配足够的空间来存储它们。
此外,只有当有趣的字符紧跟在空格后面时,这才有效,但知道它只是一个数组,我相信您可以弄清楚如何扩展它以使其忽略连续的空格。
关于c - 尝试抓取 C 中空格后的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42033597/