返回字符串中的第i个单词

时间:2015-11-06 03:23:09

标签: c arrays string pointers character

实现将在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); 
}

2 个答案:

答案 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.
}

再次指出问题:

  • 在main()中悬空指针。
  • 首选按照定义从main()返回退出代码。
  • 如果通过malloc分配内存,则总是设置内存,否则它会产生垃圾值,从而导致输出不确定。
  • 始终为null终止自行创建的字符串,因为在打印编译器时会打印所有字符,直到遇到“\ 0”。
  • 建议:不要盲目地分配101,而是找到输入字符串str的长度并分配该大小,以便它可以处理小字符串和大字符串。

答案 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"