string的查找字符串操作

想要从字符串string中查找字符可以使用find和find_first_of

 

其实我一直都是使用int来得到find这些函数的返回值的。。今天才发现,这是不对的。应该使用size_t,找不到位置的时候,并不是负数,而应该是很大的数,msdn上面说是npos

 

所以来纠正一下:

// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//
 
#include "stdafx.h"
#include "string"
#include "iostream"
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	string str = "Searches the string for the first occurrence of the sequence specified by its arguments.";
	string find_str = "the";
	size_t find_str_postion;
	find_str_postion = str.find(find_str);
	if (find_str_postion != string::npos)
	{
		cout << "found it.." << endl;
	}
	else
	{
		cout << "not found..." << endl;
	}
 
 
	return 0;
}
 


顺便来回忆一下find_first_of的用法:在父串中查找字串中的每个字符出现的首个位置,比方说测试字符为"te",父串为"zengraoli",先在父串中找t的位置,没找到,找e的位置,为1,那么此时返回1

// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//
 
#include "stdafx.h"
#include "string"
#include "iostream"
using namespace std;
#include "fstream"
 
 
int _tmain(int argc, _TCHAR* argv[])
{
	string str = "zengraoli.";
	string find_str = "te";
	size_t find_str_postion;
	find_str_postion = str.find_first_of(find_str);
	if (find_str_postion != string::npos)
	{
		cout << "pos : " << find_str_postion << endl;
		cout << "found it.." << endl;
	}
	else
	{
		cout << "not found..." << endl;
	}
 
 
	return 0;
}
 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值