如何从 ( C ) 中的另一个字符串获取子字符串

how to get sub string from another string in ( C )

我编写了一个函数,用于在 sql 查询字符串中查找 table 名称。

我的代码

char* SQLParser_GetTable(char *query)
{
char *str = "";
char *FROM="FROM";    

if(strstr(query, FROM))
{
    char *e;
    int index;      
    e = strchr(query, 'F');
    index = (int)(e - FROM);

    str=substring(str,index+4,5);
}

return  str;
}

main.c

     query = "SELECT * FROM TABLE1";
     char *tbl=SQLParser_GetTable(query);

但此代码返回完整字符串而不是 table 名称。

我的代码必须return"TABLE1".

我不知道 substring() 是什么,但这段代码符合您的想法

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *SQLParser_GetTable(char *query)
{
    char *str;
    char *FROM = "FROM ";

    /* point to the start of FORM */
    if ((str = strstr(query, FROM)) == NULL)
        return NULL;
    /* If there is only one space between FROM and TABLE1 point to it */
    str = strchr(str, ' ');
    if (str == NULL)
        return NULL;
    /* move past the ' ' character */
    str += 1;
    /* return a copy of the string */
    return strdup(str);
}

int main ()
{
    char *table = SQLParser_GetTable("SELECT * FROM TABLE1");
    if (table != NULL)
    {
        printf("%s\n", table);
        free(table);
    }
    return 0;
}

请注意,这根本不稳健,因为 FROM 和 table 名称之间可以有任意数量的空格。

我写了以下长函数,但与其他答案中的函数相比,它是唯一或多或少正确的函数。:)。该函数不考虑字母的大小写。:)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char * SQLParser_GetTable( const char *query )
{
    const char FROM[] = "FROM";    
    char *p;
    int found;

    found = ( p = strstr( query, FROM ) ) != NULL;
    found = found && ( p == query || isblank( ( unsigned char )p[-1] ) );
    found = found && ( *( p += sizeof( FROM ) - 1 ) == '[=10=]' ||
                       isblank( ( unsigned char )p[0] ) );

    if ( found )
    {
        const char *q = p;
        size_t n = 0;

        while ( isblank( ( unsigned char )*q ) ) ++q;
        while ( q[n] && !isblank( ( unsigned char )q[n] ) ) ++n;

        p = malloc( ( n + 1 ) * sizeof( char ) );

        memcpy( p, q, n );
        p[n] = '[=10=]';
    }
    else
    {
        p = NULL;
    }

    return p;
}

int main(void) 
{
    char *query = "SELECT * FROM TABLE1";
    char *p = SQLParser_GetTable( query );

    if ( p ) puts( p );

    free( p );

    return 0;
}

输出为

TABLE1