关于c++ find返回值类型 与string::nops的使用的若干问题

假设有这样的字符串“xiaobaizhu\nxiaobaizhu\xiaobaizhu”,我们只想要截取字符串第一行,而其他行不考虑。

原始方法:

通过将find("\n")输出,得到输出内容10,而采用find("sdf"),得到-1,那么得知find函数如果找不到字符串那么久返回-1

在此,我们通过以下代码实现:

int main(void) {
  string s = "xiaobaizhu\nxiaobaizhu\nruirui\n";
  string tmp = "";
  int index = s.find("\n");
  if ( index != -1) {
    cout << "index = " << index << endl;
    tmp = string(s, 0, index);
  } else {
    tmp = s;
  }
  cout << tmp << endl;
}
通过该种方法可以完成任务,而且百度知道以及其他很多博客也都是这么写的。

然后,这么写完提交代码diff后,被师傅指出了两点问题:

1、为什么要用-1,

2、find的返回值类型为何是int


关于第一个问题,我们想要用-1来表示一直到字符串的末尾也没有找到想要的字符串,而这样的值一般用std::string::npos(http://www.cplusplus.com/reference/string/string/npos/?kw=string%3A%3Anpos)来表示。

public static member constant
<string>

std::string::npos

static const size_t npos = -1;
Maximum value for size_t
npos is a static member constant value with the greatest possible value for an element of type  size_t.

This value, when used as the value for a  len (or  sublen) parameter in  string's member functions, means  "until the end of the string".

As a return value, it is usually used to indicate no matches.

This constant is defined with a value of  -1, which because  size_t is an unsigned integral type, it is the largest possible representable value for this type.

意思就是该值被定义为size_t类型,且为-1.表示知道字符串的末尾。

不同的编译系统,NOPS的值是不同的,通常为-1。但是最好把它当作常量来使用,这样安全性更高。

也就是这种表示方式  index!=std::string::npos

对于第二个问题,我们翻看find函数的返回值类型,为一个size_t类型,所以说应该将index定义为size_t类型。这个类型也是依赖编译器,或为32位,或为64位。

所以说最终的版本是这样的

int main(void) {
  string s = "xiaobaizhu\nxiaobaizhu\nruirui\n";
  string tmp = "";
  std::size_t index = s.find("\n");
  if ( index != std::string::npos) {
    cout << "index = " << index << endl;
    tmp = string(s, 0, index);
  } else {
    tmp = s;
  }
  cout << tmp << endl;
}

ok

,上班时间写的博客,比较仓促。感谢师傅yue,kailian,bowen,xunwu,还有darling   xiaobaizhu



python中也可采用find函数,但是应该用if ss.find(key) != -1:  .... 这种形式

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值