在字符串 C++ 中查找字符位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22267420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find a character position in a string C++
提问by user3395662
How can I find the position of a character in a string? Ex. If I input "abc*ab" I would like to create a new string with just "abc". Can you help me with my problem?
如何在字符串中找到字符的位置?前任。如果我输入“abc*ab”,我想用“abc”创建一个新字符串。你能帮我解决我的问题吗?
回答by
std::find
returns an iterator to the first element it finds that compares equal to what you're looking for (or the second argument if it doesn't find anything, in this case the end iterator.) You can construct a std::string
using iterators.
std::find
将迭代器返回到它找到的第一个元素,该元素与您要查找的元素相比较(如果没有找到任何内容,则返回第二个参数,在本例中为结束迭代器。)您可以std::string
使用迭代器构造一个迭代器。
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string s = "abc*ab";
std::string s2(s.begin(), std::find(s.begin(), s.end(), '*'));
std::cout << s2;
return 0;
}
回答by 6502
C++ standard string provides a find
method:
C++标准字符串提供了一种find
方法:
s.find(c)
returns the position of first instance of character c
into string s
or std::string::npos
in case the character is not present at all. You can also pass the starting index for the search; i.e.
将字符的第一个实例的位置返回c
到字符串中,s
或者std::string::npos
在字符根本不存在的情况下。您还可以传递搜索的起始索引;IE
s.find(c, x0)
will return the first index of character c
but starting the search from position x0
.
将返回字符的第一个索引,c
但从 position 开始搜索x0
。
回答by Victor
If you are working with std::string
type, then it is very easy to find the position of a character, by using std::find
algorithm like so:
如果您正在使用std::string
类型,那么通过使用如下std::find
算法很容易找到字符的位置:
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
string first_string = "abc*ab";
string truncated_string = string( first_string.cbegin(), find( first_string.cbegin(), first_string.cend(), '*' ) );
cout << truncated_string << endl;
}
Note:if your character is found multiple times in your std::string
, then the find
algorithm will return the position of the occurrence.
注意:如果你的角色在你的 中多次找到std::string
,那么find
算法将返回出现的位置。