
Linux下可以用strstr()函数定位子串所在的位置,用来实现用子串分隔一个字符串。man strstr可以看函数相关介绍
$ man strstrNAME
strstr - locate a substring
SYNOPSIS
#include <string.h>
char *strstr(const char *haystack, const char *needle)
DESCRIPTION
The strstr() function finds the first occurrence of the substring needle in the string haystack. The terminating `\0' characters are not compared.
strstr()函数实现从haystack串中,查找第一次出现的needle子串,只比较有效字符,结束符\0不算在内。
如:
#include <stdio.h>#include <string.h>
int main()
{
char s[]="abc@#123@#def@456@#ghi#789"
char sub[]="@#"
char *pc,*pb
pb=pc=s //pb指向字符串头
while( pc=strstr(pc,sub) ) //查找匹配字符串位置
{
*pc='\0' //置字符串结束符
puts(pb) //输出当前字符串
pc+=strlen(sub) //跳过分隔符串
pb=pc //pb指向新的起始位置
}
if ( pb )
puts(pb)
return 0
}
在程序当前目录下建一个txt文件bill.txt,文件内录入以下内容:
<pay_flowid>CTC4789</pay_flowid>
<>嗨,百度知道<dd>
<he和> hello linux
运行程序后在当前目录下生成str.txt文件,可以提取。
程序代码如下:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define LEN 100 /* 字符数,可以根据需要自己定义 */
int main(void)
{
int fd
long len,i,flag,j
char num[LEN],string[LEN]
fd = open("bill.txt",O_RDWR)
len = read(fd,num,LEN) /* read string for bill.txt */
num[len] = '\0'
close(fd)
for(i=0,j=0i<leni++)
{
switch(num[i])
{
case '<':
{
flag=1
break
}
case '>':
{
flag=2
break
}
default:
{
if(flag==2)
{
string[j]=num[i]
j++
}
}
}
}
string[j] = '\0'
fd = open("str.txt",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR)
if(fd)
{
write(fd,string,j)
close(fd)
}
return 0
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)