c++ - C++字符串:size_t和字符串::npos

标签 c++ c++11 c++14

我是一名初学者程序员,如果要了解代码及其工作原理,我会尽力了解这一部分。

所以这是代码:

#include <iostream>
#include <string>  //C++ Strings Library
using namespace std;

int main() {
  string s1 {};
  string wordFind {};
  s1 = "The secret word is Boo";
    cout << "Enter the word to find: ";
    cin >> wordFind;
    size_t position = s1.find(wordFind);
     if (position != string::npos)
        cout << "Found " << wordFind << " at position: " << position << endl;
     else
        cout << "Sorry! " << wordFind << " not found" << endl;
    return 0;
}

这些是我实际遇到的问题:
  • 什么是size_t,什么时候应确切使用它们?(我所知道的是,我们应该将它们用于数组索引和循环计数)
  • 为什么我们在这里使用size_t?难道不是这样吗?:
  • position = s1.find(wordFind);
  • 确切的位置是什么?(我是说它是组成的,还是C++的一部分?)
  • if条件是否意味着搜索单词直到字符串末尾?

  • 编辑:谢谢大家对我的帮助...我很感激:)

    最佳答案

    What is size_t and when should we use them exactly?(All I know is that we should use them for array indexing and loop counting)


    size_t是一个无符号整数类型,其大小足以表示C++中任何对象的大小,包括数组类型。 (大小以字节为单位)。

    Why did we use size_t here?



    因为它通常足够大,并且如果字符串大于int可以存储的最大数目,那么使用int这样的东西是不够的。从学步上来说,您应该使用std::string::size_type,无论它多大,都可以保证std::string的大小。

    couldn't it be like this?: position = s1.find(wordFind);



    不,您必须指定position的类型。或者,您可以使用auto:auto position = s1.find(wordFind);

    What is position exactly?(I mean is it made up or is it a part of C++?)



    只是一个变量,代表要搜索的子字符串(单词)的索引。

    Does the if condition mean to search the word untill the end of the string?



    它正在检查是否找到了该单词。 std::string::npos是一个特殊数字,如果找不到所需的子字符串,则std::string::find返回。

    关于c++ - C++字符串:size_t和字符串::npos,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60031225/

    相关文章:

    c++ printf float - 如何以编程方式指定精度?

    c++ - QStorageInfo 不适用于只读 rootfs

    c++ - 可变参数模板函数的扩展导致段错误

    c++ - decltype 行为背后的基本原理是什么?

    c++ - `auto` 类成员上下文中的返回类型

    c++ - 在 Ubuntu 中编译 C++ boost dynamic_bitset 代码

    c++ - 在 OS X 上编译 lsd_slam 会抛出链接错误 ld : library not found for -lGL

    c++ - 如何使存储在 vector 中的对象中的数据唯一?

    c++ - 将 std::forward_as_tuple() 结果传递给可能从该对象的右值引用成员移动的多个函数?

    c++ - 分形编程 - 有什么方法可以优化此代码以进行实时渲染?