strrchr与strchr函数 find_first_of与find_last_of

这两个是字符串的查找函数:
char buf[1024] = “Hello world\t12”;
char sep1 = ‘\t’, sep2 = ’ ‘;
char *p;
p = strrchr(buf, sep1);
表示在字符串buf中反向查找sep1字符,若找到,则返回指向该字符的指针;若没有找到,则返回NULL
p = strrchr(buf, sep2);
表示在字符串buf中正向查找sep2字符,若找到,则返回指向该字符的指针;若没有找到,则返回NULL
直接上代码吧,

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
//#define N 10240
#define LEN 10240

int main()
{
    char buf[LEN] = "test string\t12"; // the problem of char '\t'
    char sep = '\t';

    char *p;
    char buf1[LEN], buf2[LEN];
    p = strrchr(buf, sep);
    *p = '\0';
    int i = 0;
    p ++;

    int num = atoi(p);
    while(*p)
    {
        buf1[i ++] = *p;
        p ++;
    }
    p = buf;
    i = 0;
    while(*p)
    {
        buf2[i++] = *p;
        p ++;
    }   
    printf("The string is %s\n", buf2);
    printf("The number is %d\n", num);

    sep = ' ';
    char buf3[LEN], buf4[LEN];
    p = strchr(buf2, sep);
    if(p == NULL)
    {
        printf("The return is NULL\n");
        exit(-1);
    }
    *p = '\0';
    p ++;
    i = 0;
    while(*p)
    {
        buf3[i ++] = *p;
        p ++;
    }
    p = buf2;
    i = 0;
    while(*p)
    {
        buf4[i ++] = *p;
        p ++;
    }
    printf("The first string is %s,\tThe second string is %s\n", buf4, buf3);

    return 0;
}

值得一说的事情是,代码中的注释,’\t’,在用vim编辑时,tab键不代表’\t’,需要用\t来表示。


相应的在C++中string对应的函数是find_first_of与find_last_of
直接贴代码,

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
//#define N 10240
#define LEN 10240

int main()
{
    char buf[LEN] = "teststring\t12";
    char sep = '\t';
    std::string str = (std::string)buf;
    std::string str1, str2;
    std::string::size_type ind = str.find_last_of(sep);
    if(ind != std::string::npos)
    {   
        std::cout << "The test" << std::endl;
        str1 = str.substr(0, ind);
        str2 = str.substr(ind + 1, str.size());
    }   
    std::cout << "The ORG is " << (std::string)buf << std::endl;
    std::cout << "str1 : " << str1 << std::endl;
    std::cout << "str2 : " << str2 << std::endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值