到 return 字符串中的第 i 个单词

To return the ith word in the string

实施 char * ithword(char * str, int i) 将 return str 中的第 i 个单词。这些词是字母数字的,由非字母数字字符分隔。该函数将为单词 returned 和 return 指向它的指针分配内存。

我的代码:

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 == '[=11=]')
            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); 
}

我看到的一些问题,我添加了评论。

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 == '[=10=]')
            return der;
        if (isalnum(c) == 0) {
            state = 0;
            continue;
        }
        if (state == 0) {            
            state = 1;
            nw++;
        }
        if (nw == i) {
            der[counter]=c;
            counter++;
        }
    }
    der[counter] = '[=10=]'; # 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.
}

再次指出问题:

  • main() 中的悬挂指针。
  • 最好根据定义从 main() 返回退出代码。
  • 如果内存是通过 malloc 分配的,则总是 memset 内存,否则它会有垃圾值,这可能导致不确定的输出。
  • 始终以 null 终止自创建的字符串,因为在打印时编译器会打印所有字符,直到遇到“\0”。
  • 建议:不要盲目分配101,找到输入字符串str的长度并分配该大小,这样它就可以兼顾小字符串和大字符串。

也可以通过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"