首页 > 代码库 > C/C++中substr函数的应用(简单讲解)

C/C++中substr函数的应用(简单讲解)

substr(字符串,截取开始位置,截取长度) //返回截取的字

substr(‘Hello World‘,0,1) //返回结果为 ‘H‘  *从字符串第一个字符开始截取长度为1的字符串

substr(‘Hello World‘,1,1) //返回结果为 ‘H‘  *0和1都是表示截取的开始位置为第一个字符

substr(‘Hello World‘,2,4) //返回结果为 ‘ello‘

substr(‘Hello World‘,-3,3)//返回结果为 ‘rld‘ *负数(-i)表示截取的开始位置为字符串右端向左数第i个字符

测试:

select substr(‘Hello World‘,-3,3) value from dual;

 

附:java中substring(index1,index2)的简单用法

作用:从字符串索引(下标)为index1的字符开始截取长度为index2-index1 的字符串。

String str="Hello World";

System.out.println(str.substring(0,5));

打印结果为:Hello

下面给段C的代码详解,估计就懂了!

 1 #include <string.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <assert.h> 5 char* mysubstr(char* srcstr, int offset, int length) 6 { 7     assert(length > 0); 8     assert(srcstr != NULL); 9 10     int total_length = strlen(srcstr);//首先获取srcstr的长度11     //判断srcstr的长度减去需要截取的substr开始位置之后,剩下的长度12     //是否大于指定的长度length,如果大于,就可以取长度为length的子串13     //否则就把从开始位置剩下的字符串全部返回。14     int real_length = ((total_length - offset) >= length ? length : (total_length - offset)) + 1;15     char *tmp;16     if (NULL == (tmp=(char*) malloc(real_length * sizeof(char))))17     {18         printf("Memory overflow . \n");19         exit(0);20     }21     strncpy(tmp, srcstr+offset, real_length - 1);22     tmp[real_length - 1] = \0;23     return tmp;24 }25 int main()26 {27     char srcstr[] = "this is a test string!";28     char* tmp = mysubstr(srcstr, 8, 8);29     printf("TEST: result = %s\n", tmp);30     free(tmp);31     return 0;32 }

 

C/C++中substr函数的应用(简单讲解)