CCF第三题:常见的字符串函数的用法

最近在练习CCF,特意总结了一些……

1.tolower()

  • 功能:把字符转换成小写字母,非字母字符不做处理
  • 头文件:ctype.h或者stdlib.h,常用ctype.h
#include<iostream>
#include<ctype.h>
using namespace std;

int main(){
	char ch[5]={'a','B','C','d'};
	char lower_ch[5];
	for(int i=0;i<5;i++){
		lower_ch[i]=tolower(ch[i]);
		cout<<lower_ch[i];
	}
	return 0;
}

输出:abcd

2.strtok()

  • 原型:char *strtok(char *s, char *delim)
  • 功能:作用于字符串s,以包含在s中的字符delim作为分隔符,将s切分成一个个子串。strtok在参数s的字符串中发现参数delim中包含的分割字符时,会将该字符置为'\0'字符。第一次调用时,必须给予参数s字符串,往后的调用则将参数s设置成NULL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main()
{
        char ch[16] = "abc,d";
        char *p; 
        p = strtok(ch, ",");
        if(p){ 
            printf("%s\n", p); 

        }

        p = strtok(NULL, ",");
        if(p){
            printf("%s\n", p); 
        }
        return 0;
}

输出:abc  (换行)d

注:第一次以ch为第一参数,第二次执行以NULL为第一参数

3.substr()

  • 复制子字符串,要求从指定位置开始,并具有指定的长度
  • substr(开始,长度)
  • 示例代码:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
	string s1="My name is Ariel.";
	string s2 = s1.substr(1,3);
	cout<<"s2="<<s2<<endl;

	string s3=s1.substr(4);
	cout<<"s3="<<s2<<endl;
}

输出:s2=Y n

            s3=ame is Ariel.

4.insert()函数

  • 用法:void insert(int start,const string& s)
  • 功能:将子串s放入字符串中,起始于位置start。
  • 示例代码:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
	string s1="hello";
	string s2 = "Ariel!";
	s1.insert(2,s2);
	cout<<s1<<endl;
}

输出:heAriel!llo

暂时更新这么多了,欢迎补充……

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值