如何在c++中找到字符串中子字符串的位置

How to find position of a substring in string in c++?

本文关键字:字符串 位置 c++      更新时间:2023-10-16

我有一个来自命令行的字符串:

–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