2014-03-27 94 views
0

我這是從命令行來的字符串:如何找到字符串在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 ++庫的另一臺服務器上的代碼。

+0

使用getopt_long這一點。下面是一個例子:http://www.gnu.org/software/libc/manual/html_node/Getopt-Long-Option-Example.html – zoska

+0

爲什麼不使用專用的命令行解析庫,即[cpp-optparse](https ://github.com/weisslj/cpp-optparse)? –

+1

說真的,你應該考慮獲取已經處理的代碼,比如boost :: program_options。 http://www.boost.org/doc/libs/1_55_0/doc/html/program_options.html – PaulMcKenzie

回答

2

雖然確實存在許多庫可以完成您想要實現的功能(請參閱問題中的註釋),但如果您想堅持使用代碼,則必須使用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"; 
0

std::string::find_first_of(),你指望它不起作用:

中搜索匹配任何在它的參數中指定的字符 的第一個字符的字符串。

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

搜索指定由它的參數 的字符串序列的第一次出現。

但是所以你不會發明這個圓,你應該使用一個已經實現的命令行選項庫解析或者使用包含在標準庫getopt_long中的功能。

0

少言多碼!:)

#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 
相關問題