提取字符串中特定的字符(或者子字符串)
来源:互联网 发布:全民奇迹数据库密码 编辑:程序博客网 时间:2024/05/20 02:52
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main()
{
char *str1 = "g1,3,5,g7";
char *p[5];
char ptr[8];
char *mid;
mid = (char*)malloc(strlen(str1)*sizeof(char));
memcpy(mid,str1,strlen(str1)); //这一行也可以用 strcpy(mid,str1);
int i=0;
while(*mid != '\0')
{
int n;
n = strcspn(mid,",");
strncpy(ptr,mid,n);
ptr[n]='\0';
p[i]=ptr;
printf("The substring is: %s\n",p[i++]);
mid = mid+n+1;
}
return 0;
#include <string.h>
#include <malloc.h>
int main()
{
char *str1 = "g1,3,5,g7";
char *p[5];
char ptr[8];
char *mid;
mid = (char*)malloc(strlen(str1)*sizeof(char));
memcpy(mid,str1,strlen(str1)); //这一行也可以用 strcpy(mid,str1);
int i=0;
while(*mid != '\0')
{
int n;
n = strcspn(mid,",");
strncpy(ptr,mid,n);
ptr[n]='\0';
p[i]=ptr;
printf("The substring is: %s\n",p[i++]);
mid = mid+n+1;
}
return 0;
}
其实,上面这段程序是有问题的,可以把printf语句调到while循环外面,发现p[0],p[1],p[2]的值都是g7,问题出在while循环语句中的p[i]=ptr,这是因为指针传指针的问题,而我们只想传变量。我整理了一下程序,如下图。
- 提取字符串中特定的字符(或者子字符串)
- CString字符串类型中提取以特定字符分隔的子串
- 在字符串中删除特定的字符(字符串)。
- 在字符串中删除特定的字符(字符串)
- 截取字符串中特定字符之前的子串,并返回剩余子串
- 删除字符串中特定的子串
- Excel提取字符串中的特定字符
- 在字符串中删除特定的字符
- 在字符串中删除特定的字符
- 在字符串中删除特定的字符
- 在字符串中删除特定的字符
- 在字符串中删除特定的字符
- 字符串中删除特定的字符
- 在字符串中删除特定的字符
- 在字符串中删除特定的字符
- 在字符串中删除特定的字符
- 在字符串中删除特定的字符
- 在字符串中删除特定的字符
- Linux命令之dos2unix - 将DOS格式文本文件转换成UNIX格式
- 2013阿里巴巴实习笔试题 最后两题 明星问题+仓库运货
- ARP Security
- 【设计模式】代理模式
- Android 编译系统框架分析及main.mk分析
- 提取字符串中特定的字符(或者子字符串)
- Struts2拦截器的原理与实现
- 工作还没满一年别的公司想请我跳槽!
- 我的网络编程之旅
- 工厂模式学习记录
- Android eMMC booting
- 林仕鼎谈架构设计与架构师
- 苹果面试8大难题及答案
- Android 系统构架