我对编程很新,我想知道是否有办法用C中的gets()打印字符串的第一个单词?
void printFirstWord(char string[])
{
int i;
for(i = 0; i < (string[i] != '\0'); i++)
{
if(isalpha(string[i]))
printf("%c", string[i]);
}
}
int main()
{
char string[MAX];
printf("Type in a scentence");
gets(string);
printFirstWord(string);
return 0;
}
这是我现在主要编写和调用的函数。是因为我在函数中有isalpha吗?
答案 0 :(得分:1)
在您的实现中,您可以在循环中添加以下行:
if (string[i] == ' ')
break;
另外,修复你的循环参数,例如像这样:
for (i = 0; i < strlen(string); i++)
您的整体实施方式如下。 考虑根据您的评论选择另一种设计,例如不使用获取。
void printFirstWord(char string[])
{
int i;
for (i = 0; i < strlen(string); i++)
{
if (isalpha(string[i]))
printf("%c", string[i]);
if (string[i] == ' ')
break;
}
}
int main()
{
#define MAX 100
char string[MAX];
printf("Type in a scentence\n");
gets_s(string, MAX);
printFirstWord(string);
getchar();
return 0;
}
答案 1 :(得分:-1)
我刚刚找到了isblank()方法;函数,希望它对任何人都有帮助:)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main (){
int length, number, counter, position;
char name[50];
printf("Please type your complete name:\n");
gets(name);
//strlen();
//Returns the length of the given null-terminated byte string, that is, the number of characters in a character array
length=strlen(name);
//Counts each position until it finds a space
for(counter=0;counter<length;counter++)
{
if(isblank(name[counter]))
position=counter;
}
//Prints each character until the counter reaches the position number given by the counter variable
printf("\nThe first word you typed is: ");
for(number=0; number<=position; number++){
printf("%c", name[number]);
}
}