实现一个函数,能够得到某个字符串source的第pos个字串,并且字串之间使用sep分割。
int GetnSubStr(const char *source,char *buf,int pos,char sep){
return 0;
}
首先,获取源字符串的长度,避免越界。
// Get source string length.
int length;
for(length=0;source[length];length++);
然后定义一些变量:
len 字串长度计数
count 子串数量计数
mode (返回值)字串是否找到
now 当前源字符串的数组下标
int len =0;// Sub string length counter
int count=0;// Sub string counter
bool mode =0;// Getting flag
int now =0;// Offset of source string
接下来寻找第pos个字串
使用一个循环
while(now<length){
// ...
}
当前位置的字符如果是分割符sep时,需要判断是否为一个字串的结尾(因为源字符串中可能有多个相邻的分割符sep)
if(source[now]==sep){// When 'sep'
if(len){// End of sub string.
len=0;
count++;
}
}
如果不是,那么当前位置是字串的某个位置,需要判断这个字串是否为要分割的字符串
else{
if(count==pos){// Got
buffer[len]=source[now];// Write
mode=true;
}
len++;//
}
然后下一个字符
now++;// Next offset
寻找完了,返回分割(寻找)成功与否
return mode;
整个函数的代码如下
int GetnSubStr(
const char *source,
char *buffer,
const int pos ,
const char sep
){
// Get source string length.
int length;
for(length=0;source[length];length++);
// Some value
int len =0;// Sub string length counter
int count=0;// Sub string counter
bool mode =0;// Getting flag
int now =0;// Offset of source string
//
while(now<length){
if(source[now]==sep){// When 'sep'
if(len){// End of sub string.
len=0;
count++;
}
}else{
if(count==pos){// Got
buffer[len]=source[now];// Write
mode=true;
}
len++;//
}
now++;// Next offset
}
return mode;
}
--EOF--