c++常用字符串函数整理

1.strtok
ern char *strtok( char *s, const char *delim );

功能:分解字符串为一组标记串。s为要分解的字符串,delim为分隔符字符串。

说明:strtok()用来将字符串分割成一个个片段。当strtok()在参数s的字符串中发现到参数delim的分割字符时则会将该字符改为 \0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针。当没有被分割的串时则返回NULL。所有delim中包含的字符都会被滤掉,并将被滤掉的地方设为一处分割的节点。



#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}
 
2.strchr
char * strchr ( const char *str, int ch );

功能:查找字符串 str 中首次出现字符 ch 的位置
说明:返回首次出现 ch 的位置的指针,如果 str 中不存在 ch 则返回NULL。


/* strchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
    char str[] = "This is a simple string";
    char *pch;
    
    printf("Looking for the 's' character in \"%s\"...\n", str);
    pch = strchr(str, 's');
    while (pch != NULL){
        printf("found at %d th\n", pch - str + 1);
        pch = strchr(pch + 1, 's');
    }
    return 0;
}

3.substr

#include<string> #include<iostream> using namespace std; int main() {     string s("12345asdf");     string a=s.substr(0,5);//获得字符串s中 从第0位开始的长度为5的字符串//默认时的长度为从开始位置到尾     cout<<a<<endl; }



参考http://www.cplusplus.com/reference/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值