string类型size/find函数的一个坑

[C++] string类型size/find函数的一个坑

size()函数返回一个string::size_type类型的值
在32位系统上定义为 unsigned int
在64位系统上定义为 unsigned long

当unsigned int和int进行计算或者比较时,会把int转换为unsigned int。如果存在负数,转换为unsigned int会有问题。

string a = "aaa";
string b = "aaaa";
cout <<a.size()<<endl; //output: 3
cout <<b.size()<< endl;//output: 4
cout << a.size()-b.size()<< endl;//output: 18446744073709551615 
cout << int(a.size())-int(b.size())<<endl; //output: -1

所有的查找函数都返回一个size_type类型,这个返回值一般都是所找到字符串的位置string::size_type,如果没有找到,则返回string::npos 。注意,所有和string::npos的比较一定要用string::size_type来使用。

string s = "abc";
size_t p = -1;
cout << s.find('d') << endl; // output:18446744073709551615
cout << (s.find('d')== -1) << endl; //output: 1
cout << (s.find('d')== p) << endl; //output: 1
cout << min(s.find('d'), p) << endl; //output: 18446744073709551615
cout << int(s.find('d'))<< endl;// output: -1
cout << (int(s.find('d'))== -1)<< endl; //output:1

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值