C语言字符串分割
错误代码:'strsep' was not declared in this scope
谁知道如何解决?
strsep函数用于分解字符串为一组字符串。定义语句为char *strsep(char **stringp, const char *delim);
使用实例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[] = "$GPFPD,2005,266904.450,274.162,-1.111,0.504,40.1917161,116.0636047,132.93,0.011,-0.002,0.003,-1.000,16,13,0B*21";
char *buf;
buf =str;
printf("buf=%s\n",buf);
char *token;
while((token = strsep(&buf,",")) != NULL)
{
printf("%s\n",token);
}
return 0;
}
输出......
buf=$GPFPD,2005,266904.450,274.162,-1.111,0.504,40.1917161,116.0636047,132.93,0.011,-0.002,0.003,-1.000,16,13,0B*21
$GPFPD
2005
266904.450
274.162
-1.111
0.504
40.1917161
116.0636047
132.93
0.011
-0.002
0.003
-1.000
16
13
0B*21
#include <iostream>
#include <string>
using namespace std;
int main()
{
//string s = "$GPFPD,2005,266904.450,274.162,-1.111,0.504,40.1917161,116.0636047,132.93,0.011,-0.002,0.003,-1.000,16,13,0B*21";
//string sub = ",";
string s = "+CMT: \"+8618560158120\",\"\",\"22/09/28,16:24:28+32\"iloveyou";
string sub = "\"";
int index = 0;
int count = 0;
while ((index = s.find(sub, index)) < s.length())
{
cout << index << endl;
count++;
index++;
//cout << index << endl;
}
cout << count << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
//string s = "$GPFPD,2005,266904.450,274.162,-1.111,0.504,40.1917161,116.0636047,132.93,0.011,-0.002,0.003,-1.000,16,13,0B*21";
//string sub = ",";
string s = "+CMT: \"+8618560158120\",\"\",\"22/09/28,16:24:28+32\"iloveyou";
string sub = "\"";
int result[6];
int index = 0;
int j = 0;
int count = 0;
while ((index = s.find(sub, index)) < s.length())
{
result[j] = index;
j = j+1;
cout << index << endl;
count++;
index++;
//cout << index << endl;
}
cout << count << endl;
for (int i = 0; i < 6; i++)
{
cout << "arr = " << result[i] << endl;
}
//cout << endl;
return 0;
}
查找目标字符串在字符串出现的总次数
核心代码:index=s.find(c,index)
,index每次都会更新下一次找到的位置,如果没有找到跳出循环。
string s, c;
int main() {
while (cin >> s >> c) {
int index = 0;//用来存储不断更新最新找到的位置
int sum = 0;//累加出现的次数
while ((index = s.find(c,index)) != string::npos) {
cout << "sum: " << sum+1 << " index: " << index <<endl;
index += c.length();//上一次s中与c完全匹配的字符应跳过,不再比较
sum++;
}
cout << sum << endl;
}
}