c语言 指针数组初步,编程题

2024-11-28 19:38:33
推荐回答(4个)
回答(1):

#include
void split(char *str, char **a);
int main()
{
char in[10000]={0};
char *a[10000]={NULL};
int i=0;
printf("Please input a string:\n");
//输入字符串
gets(in);
//处理
split(in, a);
//输出单词
printf("Words:\n");
for(;a[i];i++) printf("%s\n", a[i]);
}
void split(char *str, char **a)
{
char *p=str;
//处理第一个单词
if(*p && *p!=' ') {*a++=str;p++;}
while(*p)
{
//处理单词
if(*p!=' ' && *(p-1)=='\0') *a++ = p;
//处理空格
else if(*p==' ') *p='\0';
p++;
}
}

回答(2):

#include
#include
#define N 10000
int main(void)
{
char str1[N],*pstr=str1;
fgets(str1,N,stdin);
char *a[N];
int n=0;
int ischanged=0;
while(*pstr!='\n')
{
if(*pstr!=' '&&!ischanged)
{
a[n++]=pstr;
ischanged=1;
}else if(*pstr==' ')
{
*pstr='\0';
ischanged=0;
}
++pstr;
}
int i;
for(i=0;i printf("%s\n",a[i]);
return 0;
}

回答(3):

#include
void GetWord(char* str)
{
char* pWord[10000];
int nNum = 0, i;
bool bSet = true;
for(; *str != '\0'; ++str)
{
if (*str == ' ')
{
*str = '\0';
bSet = true;
}
else if (bSet)
{
pWord[nNum++] = str;
bSet = false;
}
}
for (i = 0; i < nNum; i++)
{
printf("%s\n", pWord[i]);
}
}

void main()
{
char sz[] = " rtrt frerfg e wef4t4t dfgdfgdfg sdfs ef";

GetWord(sz);

}

回答(4):

void splitWords(char strSrc[], size_t len)
{
size_t i;
char **ppWords = (char **)malloc(len/2*sizeof(char *));
char **ppWord = ppWords;
memset(ppWords, 0, len/2);
*ppWord = strSrc;
for (i = 0; i < len; i++)
{
if (' ' == strSrc[i])
{
strSrc[i] = '\0';
if (i < len - 1)
{
*(++ppWord) = strSrc + i + 1;
}
}
}
for (i = 0; ppWords+i <= ppWord ; i++)
{
if (strlen(ppWords[i]) > 0)
{
printf("%s\n", ppWords[i]);
}
}
free(ppWords);
}