字符串中实用的方法

1、strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串,当strtok()在参数s的字符串中发现到参数delim的分割字符时则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针。

/*
 * 函数介绍:strtok方法,该方法可以将字符串劈开
 * 头文件:cstring
 */

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char str[20] = "what fuck it is!";
    char *p = NULL;
    p = strtok(str, " ");         //将碰到的空格值为“/0”

    while(p != NULL)
    {
        cout << p << endl;
        p = strtok(NULL, " ");
    }
}

 2、strchr查找字符串s中首次出现字符c的位置。

/*
 * 函数介绍:strchr方法,查找字符串s中首次出现字符c的位置
 * 头文件:string.h
 */

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    char str[20] = "what fuck it is!";
    char *p = NULL;
    p = strchr(str, 'u');         //获取u所在的位置
    cout << p << endl;
}


3、strrchr反向查找字符串s中首次出现字符c的位置。

/*
 * 函数介绍:strrchr方法,反向查找字符串s中首次出现字符c的位置
 * 头文件:string.h
 */

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    char str[20] = "what fuck it is!";
    char *p = NULL;
    p = strrchr(str, ' ');         //将碰到的空格值为“/0”
    cout << p << endl;
}


posted @ 2012-08-10 15:46  java简单例子  阅读(305)  评论(0编辑  收藏  举报