牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2015-10-28 投稿人: 浏览次数:2737

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

原始方法:

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

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

int main(void) {
  string s = "xiaobaizhu
xiaobaizhu
ruirui
";
  string tmp = "";
  int index = s.find("
");
  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>
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
xiaobaizhu
ruirui
";
  string tmp = "";
  std::size_t index = s.find("
");
  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:  .... 这种形式

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。