获取字符串中的子串

来源:互联网 发布:授权查询系统源码 编辑:程序博客网 时间:2024/05/21 23:32

下列代码实现了:去除字符串中空格、字符串的分割


去除字符串中空格的基本思想:从字符串第一个字符串开始遍历,若遇到空格,就将空格后的字符前移,重复直至遍历到字符串结束。


提取主字符串中的子串的基本思想:使用一字符指针数组,将主字符串中的子串分离出来,每分离出来一个子串就为该子串另外分配空间,并存入指针数组。

值得注意的是:指针数组初始时自己并不带有那么多的地址空间,它只是通过指针,来指向别的地址,因而在分离主字符串中的子串时要实行深拷贝


例:主串为:computer data structrue,那么获取出来的字串应该为computer、data、sturctrue这三个子串。


下面是具体实现:

/*trimed.cpp*author:xwz*compiler:Dev c++*2017-7-5*/#include<stdio.h>#include<stdlib.h>#include<string.h>void trim(char* str){//去除字符串str中的空格 int j,i=-1;int len = strlen(str);if(len){while(str[++i] != '\0'){if(str[i] == ' '){for(j=i; j<len; ++j)str[j] = str[j+1];}//连续两个或两个以上的空格 if(str[i] == ' ')trim(str);}}} void ExtractKeyWord(char *str,char **pstr){//将字符串str中的子串存到指针数组pstr中 int j,len,w,m,n,i=0,k=0;int nLen = strlen(str);char *p,*sub=NULL;while (i < nLen){j = i;//开始截取位置 while ((str[i] != ' ') && (str[i] != '\0'))//遇到空格 ++i;len = i - j;//截取长度 //截取字符串 if(nLen){if(sub) free(sub);if(!(sub = (char*)malloc(len*sizeof(char)+1)))exit(0);//从第主字符串j位置开始截取长度为len的字串 for(m=0,n=j; m<len && n<j+len;++m,++n) sub[m]=str[n];  sub[len] = '\0';}if (len){//实行深拷贝char *p = (char*)malloc(len*sizeof(char) + 1);w = 0;while (*(p + w) = *(sub + w++));//拷贝 pstr[k++] = p;}while (str[i] == ' ')//去除连续空格++i;}free(sub);}int main() {int i;char str1[] = "hello world";char str2[] = "computer data structrue";char *pstr[10] = {NULL};//可以存放10个字符串的指针数组 printf("before trimmed: str1 = %s\n",str1);trim(str1);printf("after trimmed: str1 = %s\n\n",str1);printf("before extract: %s\n",str2);ExtractKeyWord(str2,pstr);printf("after extract:\n");for(i=0;i<10;i++)if(pstr[i])printf("%s\n",pstr[i]);for(i=0;i<10;++i){ //释放指针数组中的堆空间 if(pstr[i]){free(pstr[i]); pstr[i] = NULL;}} getchar();return 0;}






原创粉丝点击