C++中搜索、截取字符串

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

示例中有详细注释,直接上代码:

#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
int main(void){
	string str1="hi,test,hello";
	string str2="test";
	//搜索子串,返回子串第一个字符的索引
	cout << str1.find(str2)<<endl;
	//如果不存在,返回内置常量string::npos,在一些编译器中通常为4294967295
	cout << str1.find('k')<<endl;
	//从指定索引开始搜索
	cout <<str1.find('h',2)<<endl;
	//从指定索引搜索指定字符串的前n个字符
	cout <<str1.find("her",1,2)<<endl;
	
	//在指定字符集合中搜索字符,返回其索引
	cout <<str1.find_first_of("AaEeIiOoUu")<<endl;
         //从指定索引处开始在指定字符集合中搜索字符
	cout <<str1.find_first_of("AaEeIiOoUu",2)<<endl;
         //从指定索引处开始在指定字符集合中搜索指定长度字符
	cout <<str1.find_first_of("AaEeIiOoUu",2,2)<<endl;
	
	//在指定字符集合中逆向搜索字符,返回字符最后索引,同样也具有上面另外两个重载方法
	cout <<str1.find_last_of("AaEeIiOoUu")<<endl;
	
	//查找字符串中第一个不在字符集合中的字符
	cout <<str1.find_first_not_of("AaEeIiOoUu")<<endl;
	//查找字符串中最后一个不在字符集合中的字符
	cout <<str1.find_last_not_of("AaEeIiOoUu")<<endl;
	
	//逆向搜索,也具有和find()一样的重载方法
	cout <<str1.rfind('l')<<endl;
	
	//截取子串
	string str3=str1.substr(3,4);
	cout <<str3<<endl;
	return 0;
	
}


 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
回文数是指正着读和反着读都一样的数字。在C/C++,可以使用数组和字符串来判断一个数是否为回文数。 使用数组的方法是将数字的每一位存储到数组,然后从两端开始比较,如果相同则继续比较,直到间位置。如果所有位都相同,则该数为回文数。 使用字符串的方法是将数字转换为字符串,然后从两端开始比较,如果相同则继续比较,直到间位置。如果所有字符都相同,则该数为回文数。 下面是使用数组的示例代码: ```c++ #include <iostream> using namespace std; bool isPalindrome(int num) { int digits[10]; int i = 0; while (num > 0) { digits[i++] = num % 10; num /= 10; } for (int j = 0; j < i / 2; j++) { if (digits[j] != digits[i - j - 1]) { return false; } } return true; } int main() { int num; cout << "请输入一个数字:"; cin >> num; if (isPalindrome(num)) { cout << num << " 是回文数" << endl; } else { cout << num << " 不是回文数" << endl; } return 0; } ``` 下面是使用字符串的示例代码: ```c++ #include <iostream> #include <string> using namespace std; bool isPalindrome(int num) { string str = to_string(num); int len = str.length(); for (int i = 0; i < len / 2; i++) { if (str[i] != str[len - i - 1]) { return false; } } return true; } int main() { int num; cout << "请输入一个数字:"; cin >> num; if (isPalindrome(num)) { cout << num << " 是回文数" << endl; } else { cout << num << " 不是回文数" << endl; } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

u010142437

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

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

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

打赏作者

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

抵扣说明:

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

余额充值