c++中查找字符串,并删除某个特殊子字符串中,s.find的类型问题

下面的例子展示删除字符串”ab”,具体过程是:输入好多句子,然后连成一个句子,调用函数删除。。。上代码,再解释:

#include <iostream>
#include<algorithm>
using namespace std;

void clean_str(string *str){
    string *s = str;
    cout<<*s<<endl;
    string::size_type s_t;
    string t = "ab";
    while((s_t=s->find(t, 0)) != string::npos){
        s->erase(s_t,t.length());
    }
}
int main(){
    int n, m;
    string str_all="", exam_str, key;
    cin>>n;
    getchar();
    while(n--){
        getline(cin, exam_str);
        str_all += exam_str;
    }
    clean_str(&str_all);
    cout<<"处理后:"<<str_all;
}

c++

以下解释是本人查阅资料后结合自己理解写出,如有错误,欢迎指正。。。。。

这里查找的时候,用的函数是s.find()函数,这个函数传入参数可以 s.find(查找的字符串,从那里开始查找),接收它返回值的参数是string::size_type类型,注意,这里不要定义为int类型(虽然有时候可能是对的)。。原因如下:

1、直接看c++的find定义如下。。。

1

从上面的图片转到this->find那里,跳到下面

2

大概就是说,如果要找不到就返回 npos,转到这个npos的定义:

3

可以看到,类型是size_type….

2、从http://www.cplusplus.com 查找相关定义:http://www.cplusplus.com/reference/string/string/find/ 这个是对find的定义。。。

4

转到这地方

5

接着转:

http://www.cplusplus.com/reference/cstddef/size_t/

6

找到了。。。。原文如下

Unsigned integral type
Alias of one of the fundamental unsigned integer types.
It is a type able to represent the size of any object in bytes: size_t is the type returned by the sizeof operator and is widely used in the standard library to represent sizes and counts.

大概意思是说,这个类型定义和Unsigned integral 这个类型一样(alias of),它可以表示任何对象(any object)的大小,它是通过与大小相关的操作(sizeof operator)返回的,通常在第三方库中被用来表示大小啊数量啊之类的(sizes and counts)。。。(英语太差,只能看个大概 ^_^!!!!)

现在已经基本清楚为啥不能定义为int了。。int:默认为带符号的整型,范围:2^31-1 ~ -2^31,就是2147483647 ~ -2147483648 无符号位范围:最大可以是2^32-1,就是4294967295。。。

综上所述,最简单的解释就是。。。。用int有可能溢出,最安全的定义,就是size_type啦。。。。

同样,如果find查找不到,根据c++定义,应该和 string::npos 比较,而不是和0啊或者其他什么值比较了。。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值