gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:00 25 4
gpt4 key购买 nike

我编写了一个在 sql 查询字符串中查找表名的函数。

我的代码

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;
}

主.c

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

但是这段代码返回的是完整的字符串而不是表名。

我的代码必须返回“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 和表名之间可以有任意数量的空格。

关于c - 如何从 ( C ) 中的另一个字符串获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27730828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com