分割字符串分两种,一类是以某个字符为key分割,一类是以某个串为key分割。
以串分割的
先找到key在原字符串中的位置,这个算法就多了,KMP
然后用strcnp,strcat来操作,举个例子,也是引出本次讨论的问题,http://www.youku.com:80/ok
删除:80三个字符。
char p[] = "http://www.youku.com:80/ok";
char *result = strchr(&p[5],':');
int local = result-p;
int i = 0;
int j = i+3;
while(result[j])
{
result[i] = result[j];
i++;
j++;
}
result[i] = '\0';
cout<<p<<endl;
此处没有开辟新的空间,如果写成函数也可直接返回p指针,改变了p指针指向的内容。因为问题的特殊性,招到第二个冒号的位置就可以招到:80的位置了。
第二类问题,以某个字符分割
有库函数strtok()
char *strtok(char *s, const char *delim);
strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串,当strtok()在参数s的字符串中发现到参数delim的分割字符时则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针。
char sentence[]="This is a sentence with 7 tokens";
cout<<"The string to be tokenized is:\n"<<sentence<<"\n\nThe tokens are:\n\n";
char *tokenPtr=strtok(sentence," ");
while(tokenPtr!=NULL)
{
cout<<tokenPtr<<'\n';
tokenPtr=strtok(NULL," ");
}
cout<<"After strtok, sentence = "<<sentence<<endl;
unix中有strseq()函数。