我這是從命令行來的字符串:如何找到字符串在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 ++庫的另一臺服務器上的代碼。
使用getopt_long這一點。下面是一個例子:http://www.gnu.org/software/libc/manual/html_node/Getopt-Long-Option-Example.html – zoska
爲什麼不使用專用的命令行解析庫,即[cpp-optparse](https ://github.com/weisslj/cpp-optparse)? –
說真的,你應該考慮獲取已經處理的代碼,比如boost :: program_options。 http://www.boost.org/doc/libs/1_55_0/doc/html/program_options.html – PaulMcKenzie