实现将在str中返回第i个单词的char * ithword(char * str, int i)
。单词是字母数字,由非字母数字字符分隔。该函数将为返回的单词分配内存,并返回指向它的指针。
我的代码:
char *ithword(char * str, int i)
{
/* declarations */
char *der = malloc(100 * sizeof(int));
int nw, state, j, counter;
state = 0;
nw = 0;
counter =0 ;
for(j = 0; (nw <= i) || (j < sizeof(str)); j++) {
char c = str[j];
if (c == '\0')
return der;
if (isalnum(c) == 0) {
state = 0;
continue;
}
if (state == 0) {
state = 1;
nw++;
}
if (nw == i) {
der[counter]=c;
counter++;
}
}
return der;
}
int main()
{
char *p = malloc(101);
p = ithword("bcd&acd*abc",3);
printf("%s",p);
}
答案 0 :(得分:1)
我看到的一些问题,我添加了评论。
char *ithword(char * str, int i)
{
char *der = (char *)malloc(101); # Why sizeof(int) when it has to store characters.
memset(der ,0, 101); # Always memset a malloc allocated memory else garbage value would be printed.
int nw, state, j, counter;
state = 0;
nw = 0;
counter =0 ;
for(j = 0; (nw <= i) || (j < sizeof(str)); j++) {
char c = str[j];
if (c == '\0')
return der;
if (isalnum(c) == 0) {
state = 0;
continue;
}
if (state == 0) {
state = 1;
nw++;
}
if (nw == i) {
der[counter]=c;
counter++;
}
}
der[counter] = '\0'; # The output string has to be null terminated else all the characters would be printed from the memory location until a null is encountered.
return der;
}
int main()
{
char *p = NULL; # Do not allocate here. What you did would create dangling pointer because you have allocated it and then pointed it to some other location.
p = ithword("bcd&acd*abc",3);
printf("%s",p);
return 0; # Return an exit code (0) since it has to return an int.
}
再次指出问题:
答案 1 :(得分:1)
也可以通过strtok
来解决:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "To !@ return #$ the ith word in the string";
char *p = str;
char *pch;
for( ; *p; p++ ) // replace all non-alpha characters with single space.
{
if (!isalpha(*p)) *p = ' ';
}
int i_th = 5; // the ith word to expect.
pch = strtok(str, " "); // first word.
int i = 1;
while( pch != NULL )
{
i++;
pch = strtok (NULL, " ");
if( i == i_th )
{
break;
}
}
printf( "the %dth word is \"%s\"\n", i_th, pch );
}
输出:
the 5th word is "word"