【问题标题】:How to find position of a substring in string in c++?如何在c ++中查找字符串中子字符串的位置?
【发布时间】:2014-05-06 21:55:04
【问题描述】:

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

–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++ 库。

【问题讨论】:

标签: c++ string


【解决方案1】:

虽然确实存在许多库可以完成您想要实现的事情(请参阅问题下的 cmets),但如果您想坚持使用您的代码,则必须使用 string.find 而不是 string.find_first_of。

find_first_of 从第一个参数中搜索第一次出现的 any 字符(所以 "-u")。当它找到它时,它会返回位置,因此在提供的示例中,它将返回“0”(因为–m –d Tue –t 4 20 –u userid 以- 开头)。

如果你想从给定位置搜索字符串,你可以给find一个参数来描述它应该从哪里开始:

size_t find (const string&amp; 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";

【讨论】:

    【解决方案2】:

    std::string::find_first_of() 无法正常工作:

    在字符串中搜索与任何字符匹配的第一个字符 在其参数中指定。

    你想要的是std::string::find(),其中:

    在字符串中搜索指定序列的第一次出现 通过它的论点。

    但是你不会发明这个圈子,你应该使用已经实现的命令行选项解析库之一或使用包含在标准库getopt_long功能中。

    【讨论】:

      【解决方案3】:

      字少,代码多!:)

      #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
      

      【讨论】:

        猜你喜欢
        • 2012-08-03
        • 2012-05-21
        • 1970-01-01
        • 2017-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-13
        相关资源
        最近更新 更多