解释一下substring(inputstring from (last_index+1) for len)
时间: 2023-05-24 14:02:59 浏览: 53
A:该函数用于截取字符串中从最后一个索引位置向前指定长度的子字符串。其中,inputstring为待截取的原始字符串,last_index为最后一个字符的索引位置(从1开始计数),len为需要截取的子字符串的长度。
例如,substring('Hello world', from 3 for 4)将返回‘llo ’,而substring('Hello world', from (last_index 2) for 3)将返回‘orl’。
相关问题
解释一下这串代码insert into splittable(`value`)values(substring(inputstring from (last_index+1) for len));
这段代码是一条 SQL 语句,用于将一个较长的字符串分割成若干较短的字符串,并将这些字符串分别存入数据库表 splittable 的 value 字段中。
具体地说,该语句利用了 SQL 中的 substring() 函数,其中:
- inputstring 是需要被分割的长字符串;
- last_index 是上一次已切分的子串结束位置+1(初始值为1),也就是说从上一次切分位置的下一位开始继续切分;
- len 是本次需要切分的子串长度,可以理解为分隔符在长字符串中的位置减去上一次已切分的子串结束位置,即 `substring(inputstring from last_index for len)` 返回的就是一个子字符串。
最后,该语句将切分后的子字符串插入到了 splittable 表的 value 字段中。
分析测试这段代码有几处缺陷可以该进并举例int findr(char* str, char* sub) { char *i,*j,*k,*n; int l,m; int len_str,len_sub; len_str = 0; len_sub = 0; i = str; j = sub; while(*i != '\0') { i++; len_str++; } i--; while(*j != '\0') { j++; len_sub++; } j--; n = j; for(l = len_str;l >= len_str - len_sub + 1;l--) {k = i; for(m = 1;m <= len_sub; m++) {if(*k == *j) { k--; j--; } else break; } if(m > len_sub) break; i--; j = n; } if(l < len_str - len_sub + 1) return -1; else return (l - len_sub+1);}
这段代码可能存在以下缺陷:
1. 变量命名不规范,不易读懂,例如变量i、j、k等。
2. 函数参数为char*类型时,应该考虑指针是否为空的情况,否则在访问指针所指向的空间时可能会出现非法访问。
3. 函数中未对输入的字符串长度做判断,当输入的字符串长度为0时,程序可能会出现异常。
4. 函数中存在一些冗余的代码,例如计算字符串长度时可以使用strlen函数等。
5. 函数中的算法实现可以更简洁,例如可以使用指针来实现字符串匹配。
6. 函数返回值只有-1和非负整数两种情况,无法体现具体错误信息。
下面是改进后的代码:
```
int find_substring(char* str, char* sub) {
if (str == NULL || sub == NULL) {
return -1;
}
int len_str = strlen(str);
int len_sub = strlen(sub);
if (len_str == 0 || len_sub == 0 || len_sub > len_str) {
return -1;
}
char* p = strstr(str, sub);
if (p == NULL) {
return -1;
}
return (int)(p - str);
}
```
改进后的代码使用了strstr函数查找子串,可以更简洁地实现字符串匹配。同时,增加了对参数为空和字符串长度为0的处理,返回值也更加明确。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)