我是一名初学者程序员,如果要了解代码及其工作原理,我会尽力了解这一部分。
所以这是代码:
#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);
编辑:谢谢大家对我的帮助...我很感激:)
最佳答案
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/