题目:找到输入的数字与其在句子中对应的单词并输出单词。(若输入的数字大于句子总词数,则数字大小为总词数)
方法:从计算空格数过程中判断是否与输入数匹配, 若匹配则打印直到下一个空格停止。(注意两个空格需当做一个空格算)
Word Indexing
Given a line of text and a set of index numbers, your job is to find the words indexed by that numbers. For example, consider the following line of text.
Where there is a will there is a way
In the text, the 1st word is "where", the 2nd is "there", the 3rd is "is", etc. Suppose that the given indices are 2, 1, and 5. The output is
there
Where
will
Except for declaration of array variables, you must use pointer to access array data. You also need to define the following function to fulfil the task
void getIndexedWord(const char* ptext, int index, char* pword);
Given text pointed by ptext, and an index, the function store the content of indexed word to the array pointed by pword.
Input
The input begins with a single positive integer on a line indicating the number of the cases following, each of them is described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
Each test case contains two lines of data. The first line contains a piece of text which contains alphabets and white spaces only. The length of text is no more than 2000 characters. The next line contains several nonnegative integers denoting the indices of query words. The number of indices is no more than 50.
Output
For each test case, output the indexed words line by line in the order of the query indices. If the index is larger than the maximum possible index of the given text, output the last word of the text. Place a blank line between two continuous cases.
Sample Input
2
Where there is a will there is a way
2 1 5
Somebodies knocking at your door
100 1 3 4 5
Sample Output
there
Where
will
door
Somebodies
at
your
door
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char arr[2001]={0};
char *p=arr;
int test, end=1;
scanf("%d",&test);
getchar();
while(test--)
{
getchar();
gets(arr);
if(end) end=0;
else printf("\n");
int max=1, i, len=strlen(arr);
//计算句子总共单词数
for(i=1; i<len; i++)
{
//空格后一位可能是数字,英文大小写。
if(*(p+i)>='a' && *(p+i)<='z' || *(p+i)>='A' && *(p+i)<='Z' || *(p+i)>='0' && *(p+i)<='9')
{
if(*(p+i-1)==' ') max++;
}
}
int n;
while(scanf("%d",&n)!=EOF)
{
if(n>max) n=max;
int flag=1;
for(i=0; i<len; i++)
{
//词语数与输入相同时
if(n==flag)
{
printf("%c",*(p+i));
if(*(p+i+1)==' ') break;
}
//计算词语数
//两个词语之间隔着一个空格
if(*(p+i)==' ' && *(p+i+1)!=' ') flag++;
//两个词语之间隔着两个空格,当一个空格算
else if(*(p+i)==' ' && *(p+i+1)==' ')
{
flag++;
i++;
}
}
printf("\n");
//终止扫入数字
char c;
c=getchar();
if(c=='\n') break;
}
}
return 0;
}