以下内容为个人工作中常用字符串处理小函数,若转载请加明出处。
/*
获得字符串buf中的以空格等分开的所有项的值存入vector中*/
int get_value(char *buf,vector<string> &values)
{
istringstream buf_stream(buf);
string tmp;
while(buf_stream>>tmp)
{
values.push_back(tmp);
tmp.clear();
}
return 0;
}
/*
去除字符串中的指定字符
*/
char * deleteALL(char *str,char del_char)
{
char *head,*p;
head=p=str;
while(*p)
{
if(*p!=del_char)
*str++=*p;
p++;
}
*str='\0';
return head;
}
/*
替换字符串中的指定字符
*/
char * replaceAll(char * src,char oldChar,char newChar)
{
char * head=src;
while(*src!='\0')//字符串结尾
{
if(*src==oldChar) *src=newChar; //替换指定字符
src++;
}
return head; //返回替换后的字符串首地址
}
/*
取出字符串中的标记值。
*/
void readoff(char *dbuf,char*sbuf,char *smark)
{
char *e,*f;
e=strstr(sbuf,smark);
if(e == NULL)
{
dbuf[0]='\0';
return ;
}
f=strstr(e,"\"");
f++;
e=strstr(f,"\"");
snprintf(dbuf,e -f +1,"%s\0",f);
return;
}
/*
读取整个文件的内容,返回首地址
*/
char *read_whole_file(const char *file_name)
{
FILE *fp = fopen(file_name, "r");
if (NULL == fp)
{
printf("fopen %s error", file_name);
return NULL;
}
fseek(fp, 0, SEEK_END);
int length = ftell(fp);
if(0 == length)
{
cout<<file_name<<"is empty"<<endl;
return NULL;
}
//char *buf = (char *)malloc(length + 1);
char *buf =(char *)new char[length+1];
if (NULL == buf)
{
printf("new error!\n");
fclose(fp);
return NULL;
}
bzero(buf, length + 1);
rewind(fp);
fread(buf, 1, length, fp);
fclose(fp);
return buf;
}
/*
从总缓冲区中,从cur_ptr开始,读取一行 ,每行以\n结尾
//返回本行实际长度
*/
int get_line_from_buf(char *getbuf, int buflen, const char** cur_ptr, const char *end_ptr)
{
if((*cur_ptr) == end_ptr)
{
printf("error : get_line_from_buf end of buf \n");
return -1;
}
bzero(getbuf,buflen);
int real_len=0;
char *tmpptr=getbuf;
while(*(*cur_ptr) != '\n')
{
if((*cur_ptr) == end_ptr)
{
return real_len;
}
if( *(*cur_ptr)=='\r')
{
(*cur_ptr)++;
continue;
}
*tmpptr = *(*cur_ptr);
if(real_len > buflen)
{
printf("error get_line_from_buf getbuf too small.real_len:%d,buflen:%d\n",real_len,buflen);
return -1;
}
tmpptr++;
(*cur_ptr)++;
real_len++;
}
(*cur_ptr)++;
if(*(*cur_ptr)=='\r')
{
(*cur_ptr)++;
}
return real_len;
}