字符串操作常用的函数总结

//一直都想把字符串操作常用的函数总结一些,不全但重在积累;

字符串的比较:

语法:

  int compare( const basic_string &str );
  int compare( const char *str );
  int compare( size_type index, size_type length, const basic_string &str );
  int compare( size_type index, size_type length, const basic_string &str, size_type index2,
  size_type length2 );
  int compare( size_type index, size_type length, const char *str, size_type length2 );

compare()函数以多种方式比较本字符串和str,返回:

返回值情况
小于零this < str
this == str
大于零this > str

不同的函数:

  • 比较自己和str,
  • 比较自己的子串和str,子串以index索引开始,长度为length
  • 比较自己的子串和str的子串,其中index2和length2引用str,index和length引用自己
  • 比较自己的子串和str的子串,其中str的子串以索引0开始,长度为length2,自己的子串以index开始,长度为length 

示例代码:

#include <iostream>
#include <string>
using namespace std;
int main( )
{
	string s,str;
     cin>>s>>str;
	 cout<<s.compare(str)<<endl;//相等为0,s<str ----》值为-1,否则为1;
	 cout<<s.compare(0,2,str)<<endl;
	return 0;
}

字符串带空格、Tab的输入:

语法:

  istream &getline( char *buffer, streamsize num );
  istream &getline( char *buffer, streamsize num, char delim );

getline()函数用于输入流,读取字符到buffer中,直到下列情况发生:

  • num - 1个字符已经读入,
  • 碰到一个换行标志,
  • 碰到一个EOF,
  • 或者,任意地读入,直到读到字符delimdelim字符不会被放入buffer中。

示例代码:

#include <iostream>
#include <string>
using namespace std;
int main( )
{
	string s,str;
	 getline(cin,str);
	 cin>>s;
	 cout<<str<<endl;
	 cout<<s<<endl;
	return 0;
}

字符串或字符数组的大小写转换:

代码:

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main( )
{
	string s="abcdef";
	string str="AbCDe";
	//transform()只适合字符串
	transform(s.begin(),s.end(),s.begin(),::toupper);//转换为大写
	transform(str.begin(),str.end(),str.begin(),::tolower);//转换为小写
	cout<<s<<endl;
	cout<<str<<endl;
	//字符数组的大小写转换函数
	char s1[10]={'a','B','d','R','g','H','s',};
	strlwr(s1);
	cout<<s1<<endl;
	strupr(s1);
	cout<<s1<<endl;
	return 0;
}

两个字符串的交换函数 swap( ):

代码:

#include <iostream>
#include <string>
using namespace std;
int main( )
{
	string first="This comes first" ;
    string second="And this is second" ;
    first.swap( second );
    cout<<first<<endl;
    cout<<second<<endl;

	return 0;
}

返回字符串的长度

#include <bits/stdc++.h>
using namespace std;
int main() {
	string s;
	getline(cin,s);
	char chr[6]={'a','b','c'};
	cout<<strlen(chr)<<endl;//只适用于字符数组
	cout<<s.length()<<endl;//只适用于字符串
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hello689

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值