如何在c++中找到字符串中子字符串的位置
How to find position of a substring in string in c++?
我有一个来自命令行的字符串:
–m –d Tue –t 4 20 –u userid
我将它保存为一个字符串:
string command;
for(int i=1; i<argc;i++){
string tmp = argv[i];
command += " "+ tmp + " ";
}
现在我想操作这个字符串来查找是否有-u,如果有-u,我想看看下一个值是以-开头还是一个名字。(只能是-u或-u和用户名。在这个例子中,有一个用户名)
if(command.find("-u",0)){
std::size_t found = command.find_first_of("-u");
cout<<found<<endl;
}
输出是14,这不是正确的位置。我的工作是查找是否有一个-u,如果-u之后是一个用户名,或者什么都没有,或者另一个以-开头的命令。我欣赏任何想法或有效的代码。
编辑:我必须在另一个服务器上运行这段代码,我不能接受任何库而不是内置的g++库。
虽然确实存在许多库可以完成您想要实现的事情(请参阅问题下的注释),但如果您想坚持使用您的代码,则必须使用string.find
而不是string.find_first_of
。
find_first_of
从第一个参数中搜索第一个出现的字符(因此"-u"
)。当它找到它时,它返回位置,因此在提供的示例中,它将返回"0"(因为–m –d Tue –t 4 20 –u userid
以-
开头)。
如果你想从给定的位置搜索字符串,你可以给find
一个参数来描述它应该从哪个位置开始:
size_t find (const string& str, size_t pos = 0) const;
所以,如果你想找到"-u"之后的第一个"-",你可以这样做:
// Check if the first thing after "-u" starts with "-":
if(command.find("-u")!=string::npos // if there's an "-u" in the command,
&& (command.find("-",command.find("-u")) // and there's a "-" with a position
< command.find_first_of("abcdefghijklmnoqprstuwvxys",command.find("-u"))) // less than the position of the first letter after "-u", then:
cout << "it's a different command";
std::string::find_first_of()
不像你期望的那样工作:
在字符串中搜索与任何字符匹配的第一个字符在其参数中指定。
你想要的是std::string::find()
,它:
在字符串中查找指定序列的第一个出现项
但是你不会发明圆圈,你应该使用一个已经实现的命令行选项解析库,或者使用标准库中包含的getopt_long
功能。
字少代码多
#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <string>
int main()
{
const char *user = "–u";
std::string s( "–m –d Tue –t 4 20 –u userid" );
std::string userID;
std::istringstream is( s );
auto it = std::find( std::istream_iterator<std::string>( is ),
std::istream_iterator<std::string>(),
user );
if ( it != std::istream_iterator<std::string>() )
{
++it;
if ( it != std::istream_iterator<std::string>() && ( *it )[0] != '-' )
{
userID = *it;
}
}
std::cout << "userID = " << userID << std::endl;
}
输出为
userID = userid
- 如何将元素添加到向量的字符串位置
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 为什么字符串的 move() 会改变内存中底层数据的位置?
- 返回员工和工资(给定位置子字符串)
- 将文件复制到自定义位置,存在字符串转换问题
- 替换字符串位置 X 中的单词C++
- 在特定位置为字符串添加空格
- 计算在同一位置至少包含一个常用字符的不同字符串对
- 如何在另一个字符串的x位置插入一个字符串?
- 我如何知道字符串中字符相对于英文字母的位置值?
- C++ - 重置字符串流不会重置获取位置或清除标志吗?
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 如何从字符串向量中选择第 n 个位置?
- 如何从输入字符串中提取特定位置的字符?
- C++字符串_Xout_of_range("无效的字符串位置");
- 将字符数复制到新字符串位置的字符串操作,例如 S[0]
- 如何从字符串位置构造CSTRING/STD :: String
- 如何在 boost::regex 中找到子匹配的字符串位置
- 空字符串位置返回为*
- 如果我将一个值赋给一个目前不使用的字符串位置,究竟会发生什么?