どうすれば入手することができますか :
connect
100
username
example
この文字列から:
ngg://connect>100/username>example/
std::string::find
引数"/"
と">"
およびを使用しstd::string::substr
て、見つかったインデックスを使用します。
これは良いスタートです。
ngg://connect>100/username>example/
この形式が固定されている場合は、次のように使用できますstd::sscanf
。
#include <iostream>
#include <cstdio>
int main()
{
char const *input = "ngg://connect>100/username>example/";
char const *input_format = "ngg://%[^>]>%d/%[^>]>%[^/]";
char connect[100], user[100], str[100]; //assuming max size is 100
int num;
if ( std::sscanf(input, input_format, connect, &num, user, str) != 4 )
{
std::cerr<<"error - number of tokens read must be equal to 4";
return 0;
}
std::cout << connect <<std::endl;
std::cout << num <<std::endl;
std::cout << user <<std::endl;
std::cout << str <<std::endl;
}
出力 (オンライン デモ):
connect
100
username
example
可能性は次のboost::split()
とおりです。
#include <iostream>
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
int main()
{
std::vector<std::string> tokens;
std::string s("ngg://connect>100/username>example/");
boost::split(tokens, s, boost::is_any_of("/>"));
// "connect" == tokens[2]
// "100" == tokens[3]
// "username" == tokens[4]
// "example" == tokens[5]
return 0;
}
strtok
多様性のために答えを追加する:
char str[] = "ngg://connect>100/username>example/";
char *s = strtok(str, ">/");
std::vector<std::string> tokens;
while (s = strtok(NULL, ">/"))
tokens.push_back(std::string(s));
これにより、文字列str
が目的のトークンに分割されます(ngg:
質問のように最初の を破棄します)。このコードの実際の例を
次に示します。