C语言字符串分割

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;
  }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值