如何检查c++ 是否从一个特定的字符串开始,并将子字符串转换为int?

时间:2022-09-01 14:22:56

How do I do the following (Python pseudocode) in C++?

如何在c++中执行以下操作(Python伪代码)?

if argv[1].startswith('--foo='):
    foo_value = int(argv[1][len('--foo='):])

(For example, if argv[1] is '--foo=98', then foo_value is 98.)

(例如,如果argv[1]是'- foo=98',那么foo_value是98。)

Update: I'm hesitant to look into Boost, since I'm just looking at making a very small change to a simple little command-line tool. (I'd rather not have to learn how to link in and use Boost for a minor change.)

更新:我不太愿意研究Boost,因为我只是想对一个简单的命令行工具做一个很小的更改。(我宁愿不需要学习如何链接和使用Boost进行微小更改。)

19 个解决方案

#1


101  

If you're using Boost, you can do it with boost string algorithms + boost lexical cast:

如果你使用Boost,你可以使用Boost字符串算法+ Boost词汇转换:

#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>

try {    
    if (boost::starts_with(argv[1], "--foo="))
        foo_value = boost::lexical_cast<int>(argv[1]+6);
} catch (boost::bad_lexical_cast) {
    // bad parameter
}

Like most boost libraries, string algorithm & lexical cast are header-only, there's nothing to link in.

就像大多数boost库一样,字符串算法和词法转换都是头向的,没有什么可链接的。

This kind of approach, like many of the other answers provided here is ok for very simple tasks, but in the long run you are usually better off using a command line parsing library. Boost has one (Boost.Program_options), which may make sense if you happen to be using Boost already.

这种方法,就像这里提供的许多其他答案一样,对于非常简单的任务来说是可以的,但是从长远来看,最好使用命令行解析库。Boost有一个(boot . program_options),如果您碰巧已经在使用Boost,那么这个选项可能是有意义的。

Otherwise a search for "c++ command line parser" will yield a number of options.

否则,搜索“c++命令行解析器”将产生许多选项。

#2


161  

You would do it like this:

你会这样做:

   std::string prefix("--foo=");
   if (!arg.compare(0, prefix.size(), prefix))
      foo_value = atoi(arg.substr(prefix.size()).c_str());

Looking for a lib such as Boost.ProgramOptions that does this for you is also a good idea.

寻找一个像Boost这样的库。为您提供的编程选项也是一个好主意。

#3


102  

Just for completeness, I will mention the C way to do it:

为了完整起见,我将提及C方法:

If str is your original string, substr is the substring you want to check, then

如果str是原始字符串,那么substr是要检查的子字符串

strncmp(str, substr, strlen(substr))

strncmp(str,substr strlen(substr))

will return 0 if str starts with substr. The functions strncmp and strlen are in the C header file <string.h>

如果str以substr开始,则返回0。strncmp和strlen函数在C头文件

(originally posted by Yaseen Rauf here, markup added)

(最初由Yaseen Rauf在这里发布,添加了标记)

For a case-insensitive comparison, use strnicmp instead of strncmp.

对于不区分大小写的比较,使用strnicmp而不是strncmp。

This is the C way to do it, for C++ strings you can use the same function like this:

这是C的方法,对于c++字符串你可以使用相同的函数:

strncmp(str.c_str(), substr.c_str(), substr.size())

#4


80  

std::string s = "tititoto";
if (s.rfind("titi", 0) == 0) {
  // s starts with prefix
}

Who needs anything else? Pure STL!

谁还需要别的吗?纯STL !

#5


74  

Code I use myself:

我使用代码:

std::string prefix = "-param=";
std::string argument = argv[1];
if(argument.substr(0, prefix.size()) == prefix) {
    std::string argumentValue = argument.substr(prefix.size());
}

#6


35  

Nobody used the STL algorithm/mismatch function yet. If this returns true, prefix is a prefix of 'toCheck':

还没有人使用STL算法/错配函数。如果返回true,前缀是“toCheck”的前缀:

std::mismatch(prefix.begin(), prefix.end(), toCheck.begin()).first == prefix.end()

Full example prog:

完整的示例食物:

#include <algorithm>
#include <string>
#include <iostream>

int main(int argc, char** argv) {
    if (argc != 3) {
        std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
                  << "Will print true if 'prefix' is a prefix of string" << std::endl;
        return -1;
    }
    std::string prefix(argv[1]);
    std::string toCheck(argv[2]);
    if (prefix.length() > toCheck.length()) {
        std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
                  << "'prefix' is longer than 'string'" <<  std::endl;
        return 2;
    }
    if (std::mismatch(prefix.begin(), prefix.end(), toCheck.begin()).first == prefix.end()) {
        std::cout << '"' << prefix << '"' << " is a prefix of " << '"' << toCheck << '"' << std::endl;
        return 0;
    } else {
        std::cout << '"' << prefix << '"' << " is NOT a prefix of " << '"' << toCheck << '"' << std::endl;
        return 1;
    }
}

Edit:

编辑:

As @James T. Huggett suggests, std::equal is a better fit for the question: Is A a prefix of B? and is slight shorter code:

正如@James T. Huggett认为的那样,std: equal更适合这个问题:a的前缀是B吗?代码稍短:

std::equal(prefix.begin(), prefix.end(), toCheck.begin())

Full example prog:

完整的示例食物:

#include <algorithm>
#include <string>
#include <iostream>

int main(int argc, char **argv) {
  if (argc != 3) {
    std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
              << "Will print true if 'prefix' is a prefix of string"
              << std::endl;
    return -1;
  }
  std::string prefix(argv[1]);
  std::string toCheck(argv[2]);
  if (prefix.length() > toCheck.length()) {
    std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
              << "'prefix' is longer than 'string'" << std::endl;
    return 2;
  }
  if (std::equal(prefix.begin(), prefix.end(), toCheck.begin())) {
    std::cout << '"' << prefix << '"' << " is a prefix of " << '"' << toCheck
              << '"' << std::endl;
    return 0;
  } else {
    std::cout << '"' << prefix << '"' << " is NOT a prefix of " << '"'
              << toCheck << '"' << std::endl;
    return 1;
  }
}

#7


21  

Given that both strings — argv[1] and "--foo" — are C strings, @FelixDombek's answer is hands-down the best solution.

考虑到这两个字符串——argv[1]和“-foo”——都是C字符串,@FelixDombek的答案无疑是最好的解决方案。

Seeing the other answers, however, I thought it worth noting that, if your text is already available as a std::string, then a simple, zero-copy, maximally efficient solution exists that hasn't been mentioned so far:

然而,看到其他的答案,我认为值得注意的是,如果您的文本已经作为std::string提供,那么就存在一个简单的、零拷贝的、最高效率的解决方案,这是迄今为止没有提到的:

const char * foo = "--foo";
if (text.rfind(foo, 0) == 0)
    foo_value = text.substr(strlen(foo));

And if foo is already a string:

如果foo已经是字符串:

std::string foo("--foo");
if (text.rfind(foo, 0) == 0)
    foo_value = text.substr(foo.length());

#8


9  

At the risk of being flamed for using C constructs, I do think this sscanf example is more elegant than most Boost solutions. And you don't have to worry about linkage if you're running anywhere that has a Python interpreter!

冒着使用C构造的风险,我认为这个sscanf示例比大多数Boost解决方案更优雅。如果您在任何有Python解释器的地方运行,那么您不必担心链接问题!

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    for (int i = 1; i != argc; ++i) {
        int number = 0;
        int size = 0;
        sscanf(argv[i], "--foo=%d%n", &number, &size);
        if (size == strlen(argv[i])) {
            printf("number: %d\n", number);
        }
        else {
            printf("not-a-number\n");
        }
    }
    return 0;
}

Here's some example output that demonstrates the solution handles leading/trailing garbage as correctly as the equivalent Python code, and more correctly than anything using atoi (which will erroneously ignore a non-numeric suffix).

这里有一些示例输出,它演示了解决方案如何像处理等效的Python代码一样正确地处理引导/跟踪垃圾,并且比使用atoi的任何东西都更正确(atoi将错误地忽略非数字后缀)。

$ ./scan --foo=2 --foo=2d --foo='2 ' ' --foo=2'
number: 2
not-a-number
not-a-number
not-a-number

#9


7  

Using STL this could look like:

使用STL,可以如下所示:

std::string prefix = "--foo=";
std::string arg = argv[1];
if (prefix.size()<=arg.size() && std::equal(prefix.begin(), prefix.end(), arg.begin())) {
  std::istringstream iss(arg.substr(prefix.size()));
  iss >> foo_value;
}

#10


6  

Why not use gnu getopts? Here's a basic example (without safety checks):

为什么不使用gnu getopts?这里有一个基本的例子(没有安全检查):

#include <getopt.h>
#include <stdio.h>

int main(int argc, char** argv)
{
  option long_options[] = {
    {"foo", required_argument, 0, 0},
    {0,0,0,0}
  };

  getopt_long(argc, argv, "f:", long_options, 0);

  printf("%s\n", optarg);
}

For the following command:

下面的命令:

$ ./a.out --foo=33

You will get

你会得到

33

#11


4  

I use std::string::compare wrapped in utility method like below:

我使用了std::string:::比较用实用的方法包装如下:

static bool startsWith(const string& s, const string& prefix) {
    return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0;
}

#12


3  

You can also use strstr:

你也可以使用strstr:

if (strstr(str, substr) == substr) {
    // 'str' starts with 'substr'
}

but I think it's good only for short strings because it has to loop through the whole string when the string doesn't actually start with 'substr'.

但我认为它只适用于短字符串因为当字符串不是以substr开头时它必须对整个字符串进行循环。

#13


2  

Ok why the complicated use of libraries and stuff? C++ String objects overload the [] operator, so you can just compare chars.. Like what I just did, because I want to list all files in a directory and ignore invisible files and the .. and . pseudofiles.

为什么图书馆和其他东西的使用很复杂呢?c++ String对象重载了[]运算符,因此您可以比较chars。就像我刚才做的那样,因为我想要列出目录中的所有文件,忽略不可见的文件和。和。pseudofiles。

    while ((ep = readdir(dp)))
    {
        string s(ep->d_name);
        if(!(s[0] == '.'))      // Omit invisible files and .. or .
            files.push_back(s);
    }

It's that simple..

就这么简单…

#14


1  

text.substr(0, start.length()) == start

#15


0  

std::string text = "--foo=98";
std::string start = "--foo=";

if (text.find(start) == 0)
{
    int n = stoi(text.substr(start.length()));
    std::cout << n << std::endl;
}

#16


0  

although I'm 8 years late to the party, here's the simplest, DIY way to do it:

尽管我晚了8年才参加聚会,但最简单的DIY方式是:

#include <iostream>
#include <string>

using namespace std; // for clarity's sake.

bool startswith(string prefix, string text) {
    if (prefix.length() > 0 && text.length() > prefix.length()) {
        int i = 0;
        while (i < prefix.length()) {
            if (text[i] != prefix[i]) return false;
            i++;
        }
        return true;
    }

    else return false;
}

int main (int argc, char* argv) {
    if(startswith("--foo=", argv[1]))
        // do something about it!
}

#17


0  

With C++17 you can use std::basic_string_view & with C++20 std::basic_string::starts_with or std::basic_string_view::starts_with.

使用c++ 17,您可以使用std::basic_string_view &与c++ 20 std:::basic_string::starts_with或std::basic_string_view::starts_with。

The benefit of std::string_view in comparison to std::string - regarding memory management - is that it only holds a pointer to a "string" (contiguous sequence of char-like objects) and knows its size. Example without moving/copying the source strings just to get the integer value:

std::string_view与std::string——关于内存管理——的好处是,它只持有一个指向“string”(类似于charlesobject的连续序列)的指针,并且知道它的大小。例如,无需移动/复制源字符串就可以获得整数值:

#include <string_view>
#include <exception>
#include <iostream>

const char * argument = "--foo=42"; // Emulating command argument.
const char * argumentPrefix = "--foo";
int inputValue = 0;

std::string_view argView = argument;
if (argView.starts_with(argumentPrefix))
{
    std::string_view prefixView = argumentPrefix; // Helper for getting the size of argumentPrefix.
    try
    {
        // The underlying data of argView is nul-terminated, therefore we can use data().
        inputValue = std::atoi(argView.substr(prefixView.size() + 1).data());
    }
    catch (std::exception& e)
    {
        std::cerr << e.what();
    }
}

#18


0  

Since C++11 also std::regex_search can be used, e.g. as follows (returns an empty string on failure):

因为c++ 11也可以使用std::regex_search,例如如下(失败时返回空字符串):

#include <regex>

std::string startsWith(const std::string &str, const std::string &prefix) {
  std::smatch match;
  std::regex_search(str, match, std::regex("^" + prefix));
  return match.suffix();
}

#19


-3  

if(boost::starts_with(string_to_search, string_to_look_for))
    intval = boost::lexical_cast<int>(string_to_search.substr(string_to_look_for.length()));

This is completely untested. The principle is the same as the Python one. Requires Boost.StringAlgo and Boost.LexicalCast.

这是完全测试。原理与Python相同。需要提高。StringAlgo Boost.LexicalCast。

Check if the string starts with the other string, and then get the substring ('slice') of the first string and convert it using lexical cast.

检查字符串是否从另一个字符串开始,然后获取第一个字符串的子字符串('slice'),并使用lexical cast将其转换为字符串。

#1


101  

If you're using Boost, you can do it with boost string algorithms + boost lexical cast:

如果你使用Boost,你可以使用Boost字符串算法+ Boost词汇转换:

#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>

try {    
    if (boost::starts_with(argv[1], "--foo="))
        foo_value = boost::lexical_cast<int>(argv[1]+6);
} catch (boost::bad_lexical_cast) {
    // bad parameter
}

Like most boost libraries, string algorithm & lexical cast are header-only, there's nothing to link in.

就像大多数boost库一样,字符串算法和词法转换都是头向的,没有什么可链接的。

This kind of approach, like many of the other answers provided here is ok for very simple tasks, but in the long run you are usually better off using a command line parsing library. Boost has one (Boost.Program_options), which may make sense if you happen to be using Boost already.

这种方法,就像这里提供的许多其他答案一样,对于非常简单的任务来说是可以的,但是从长远来看,最好使用命令行解析库。Boost有一个(boot . program_options),如果您碰巧已经在使用Boost,那么这个选项可能是有意义的。

Otherwise a search for "c++ command line parser" will yield a number of options.

否则,搜索“c++命令行解析器”将产生许多选项。

#2


161  

You would do it like this:

你会这样做:

   std::string prefix("--foo=");
   if (!arg.compare(0, prefix.size(), prefix))
      foo_value = atoi(arg.substr(prefix.size()).c_str());

Looking for a lib such as Boost.ProgramOptions that does this for you is also a good idea.

寻找一个像Boost这样的库。为您提供的编程选项也是一个好主意。

#3


102  

Just for completeness, I will mention the C way to do it:

为了完整起见,我将提及C方法:

If str is your original string, substr is the substring you want to check, then

如果str是原始字符串,那么substr是要检查的子字符串

strncmp(str, substr, strlen(substr))

strncmp(str,substr strlen(substr))

will return 0 if str starts with substr. The functions strncmp and strlen are in the C header file <string.h>

如果str以substr开始,则返回0。strncmp和strlen函数在C头文件

(originally posted by Yaseen Rauf here, markup added)

(最初由Yaseen Rauf在这里发布,添加了标记)

For a case-insensitive comparison, use strnicmp instead of strncmp.

对于不区分大小写的比较,使用strnicmp而不是strncmp。

This is the C way to do it, for C++ strings you can use the same function like this:

这是C的方法,对于c++字符串你可以使用相同的函数:

strncmp(str.c_str(), substr.c_str(), substr.size())

#4


80  

std::string s = "tititoto";
if (s.rfind("titi", 0) == 0) {
  // s starts with prefix
}

Who needs anything else? Pure STL!

谁还需要别的吗?纯STL !

#5


74  

Code I use myself:

我使用代码:

std::string prefix = "-param=";
std::string argument = argv[1];
if(argument.substr(0, prefix.size()) == prefix) {
    std::string argumentValue = argument.substr(prefix.size());
}

#6


35  

Nobody used the STL algorithm/mismatch function yet. If this returns true, prefix is a prefix of 'toCheck':

还没有人使用STL算法/错配函数。如果返回true,前缀是“toCheck”的前缀:

std::mismatch(prefix.begin(), prefix.end(), toCheck.begin()).first == prefix.end()

Full example prog:

完整的示例食物:

#include <algorithm>
#include <string>
#include <iostream>

int main(int argc, char** argv) {
    if (argc != 3) {
        std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
                  << "Will print true if 'prefix' is a prefix of string" << std::endl;
        return -1;
    }
    std::string prefix(argv[1]);
    std::string toCheck(argv[2]);
    if (prefix.length() > toCheck.length()) {
        std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
                  << "'prefix' is longer than 'string'" <<  std::endl;
        return 2;
    }
    if (std::mismatch(prefix.begin(), prefix.end(), toCheck.begin()).first == prefix.end()) {
        std::cout << '"' << prefix << '"' << " is a prefix of " << '"' << toCheck << '"' << std::endl;
        return 0;
    } else {
        std::cout << '"' << prefix << '"' << " is NOT a prefix of " << '"' << toCheck << '"' << std::endl;
        return 1;
    }
}

Edit:

编辑:

As @James T. Huggett suggests, std::equal is a better fit for the question: Is A a prefix of B? and is slight shorter code:

正如@James T. Huggett认为的那样,std: equal更适合这个问题:a的前缀是B吗?代码稍短:

std::equal(prefix.begin(), prefix.end(), toCheck.begin())

Full example prog:

完整的示例食物:

#include <algorithm>
#include <string>
#include <iostream>

int main(int argc, char **argv) {
  if (argc != 3) {
    std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
              << "Will print true if 'prefix' is a prefix of string"
              << std::endl;
    return -1;
  }
  std::string prefix(argv[1]);
  std::string toCheck(argv[2]);
  if (prefix.length() > toCheck.length()) {
    std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
              << "'prefix' is longer than 'string'" << std::endl;
    return 2;
  }
  if (std::equal(prefix.begin(), prefix.end(), toCheck.begin())) {
    std::cout << '"' << prefix << '"' << " is a prefix of " << '"' << toCheck
              << '"' << std::endl;
    return 0;
  } else {
    std::cout << '"' << prefix << '"' << " is NOT a prefix of " << '"'
              << toCheck << '"' << std::endl;
    return 1;
  }
}

#7


21  

Given that both strings — argv[1] and "--foo" — are C strings, @FelixDombek's answer is hands-down the best solution.

考虑到这两个字符串——argv[1]和“-foo”——都是C字符串,@FelixDombek的答案无疑是最好的解决方案。

Seeing the other answers, however, I thought it worth noting that, if your text is already available as a std::string, then a simple, zero-copy, maximally efficient solution exists that hasn't been mentioned so far:

然而,看到其他的答案,我认为值得注意的是,如果您的文本已经作为std::string提供,那么就存在一个简单的、零拷贝的、最高效率的解决方案,这是迄今为止没有提到的:

const char * foo = "--foo";
if (text.rfind(foo, 0) == 0)
    foo_value = text.substr(strlen(foo));

And if foo is already a string:

如果foo已经是字符串:

std::string foo("--foo");
if (text.rfind(foo, 0) == 0)
    foo_value = text.substr(foo.length());

#8


9  

At the risk of being flamed for using C constructs, I do think this sscanf example is more elegant than most Boost solutions. And you don't have to worry about linkage if you're running anywhere that has a Python interpreter!

冒着使用C构造的风险,我认为这个sscanf示例比大多数Boost解决方案更优雅。如果您在任何有Python解释器的地方运行,那么您不必担心链接问题!

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    for (int i = 1; i != argc; ++i) {
        int number = 0;
        int size = 0;
        sscanf(argv[i], "--foo=%d%n", &number, &size);
        if (size == strlen(argv[i])) {
            printf("number: %d\n", number);
        }
        else {
            printf("not-a-number\n");
        }
    }
    return 0;
}

Here's some example output that demonstrates the solution handles leading/trailing garbage as correctly as the equivalent Python code, and more correctly than anything using atoi (which will erroneously ignore a non-numeric suffix).

这里有一些示例输出,它演示了解决方案如何像处理等效的Python代码一样正确地处理引导/跟踪垃圾,并且比使用atoi的任何东西都更正确(atoi将错误地忽略非数字后缀)。

$ ./scan --foo=2 --foo=2d --foo='2 ' ' --foo=2'
number: 2
not-a-number
not-a-number
not-a-number

#9


7  

Using STL this could look like:

使用STL,可以如下所示:

std::string prefix = "--foo=";
std::string arg = argv[1];
if (prefix.size()<=arg.size() && std::equal(prefix.begin(), prefix.end(), arg.begin())) {
  std::istringstream iss(arg.substr(prefix.size()));
  iss >> foo_value;
}

#10


6  

Why not use gnu getopts? Here's a basic example (without safety checks):

为什么不使用gnu getopts?这里有一个基本的例子(没有安全检查):

#include <getopt.h>
#include <stdio.h>

int main(int argc, char** argv)
{
  option long_options[] = {
    {"foo", required_argument, 0, 0},
    {0,0,0,0}
  };

  getopt_long(argc, argv, "f:", long_options, 0);

  printf("%s\n", optarg);
}

For the following command:

下面的命令:

$ ./a.out --foo=33

You will get

你会得到

33

#11


4  

I use std::string::compare wrapped in utility method like below:

我使用了std::string:::比较用实用的方法包装如下:

static bool startsWith(const string& s, const string& prefix) {
    return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0;
}

#12


3  

You can also use strstr:

你也可以使用strstr:

if (strstr(str, substr) == substr) {
    // 'str' starts with 'substr'
}

but I think it's good only for short strings because it has to loop through the whole string when the string doesn't actually start with 'substr'.

但我认为它只适用于短字符串因为当字符串不是以substr开头时它必须对整个字符串进行循环。

#13


2  

Ok why the complicated use of libraries and stuff? C++ String objects overload the [] operator, so you can just compare chars.. Like what I just did, because I want to list all files in a directory and ignore invisible files and the .. and . pseudofiles.

为什么图书馆和其他东西的使用很复杂呢?c++ String对象重载了[]运算符,因此您可以比较chars。就像我刚才做的那样,因为我想要列出目录中的所有文件,忽略不可见的文件和。和。pseudofiles。

    while ((ep = readdir(dp)))
    {
        string s(ep->d_name);
        if(!(s[0] == '.'))      // Omit invisible files and .. or .
            files.push_back(s);
    }

It's that simple..

就这么简单…

#14


1  

text.substr(0, start.length()) == start

#15


0  

std::string text = "--foo=98";
std::string start = "--foo=";

if (text.find(start) == 0)
{
    int n = stoi(text.substr(start.length()));
    std::cout << n << std::endl;
}

#16


0  

although I'm 8 years late to the party, here's the simplest, DIY way to do it:

尽管我晚了8年才参加聚会,但最简单的DIY方式是:

#include <iostream>
#include <string>

using namespace std; // for clarity's sake.

bool startswith(string prefix, string text) {
    if (prefix.length() > 0 && text.length() > prefix.length()) {
        int i = 0;
        while (i < prefix.length()) {
            if (text[i] != prefix[i]) return false;
            i++;
        }
        return true;
    }

    else return false;
}

int main (int argc, char* argv) {
    if(startswith("--foo=", argv[1]))
        // do something about it!
}

#17


0  

With C++17 you can use std::basic_string_view & with C++20 std::basic_string::starts_with or std::basic_string_view::starts_with.

使用c++ 17,您可以使用std::basic_string_view &与c++ 20 std:::basic_string::starts_with或std::basic_string_view::starts_with。

The benefit of std::string_view in comparison to std::string - regarding memory management - is that it only holds a pointer to a "string" (contiguous sequence of char-like objects) and knows its size. Example without moving/copying the source strings just to get the integer value:

std::string_view与std::string——关于内存管理——的好处是,它只持有一个指向“string”(类似于charlesobject的连续序列)的指针,并且知道它的大小。例如,无需移动/复制源字符串就可以获得整数值:

#include <string_view>
#include <exception>
#include <iostream>

const char * argument = "--foo=42"; // Emulating command argument.
const char * argumentPrefix = "--foo";
int inputValue = 0;

std::string_view argView = argument;
if (argView.starts_with(argumentPrefix))
{
    std::string_view prefixView = argumentPrefix; // Helper for getting the size of argumentPrefix.
    try
    {
        // The underlying data of argView is nul-terminated, therefore we can use data().
        inputValue = std::atoi(argView.substr(prefixView.size() + 1).data());
    }
    catch (std::exception& e)
    {
        std::cerr << e.what();
    }
}

#18


0  

Since C++11 also std::regex_search can be used, e.g. as follows (returns an empty string on failure):

因为c++ 11也可以使用std::regex_search,例如如下(失败时返回空字符串):

#include <regex>

std::string startsWith(const std::string &str, const std::string &prefix) {
  std::smatch match;
  std::regex_search(str, match, std::regex("^" + prefix));
  return match.suffix();
}

#19


-3  

if(boost::starts_with(string_to_search, string_to_look_for))
    intval = boost::lexical_cast<int>(string_to_search.substr(string_to_look_for.length()));

This is completely untested. The principle is the same as the Python one. Requires Boost.StringAlgo and Boost.LexicalCast.

这是完全测试。原理与Python相同。需要提高。StringAlgo Boost.LexicalCast。

Check if the string starts with the other string, and then get the substring ('slice') of the first string and convert it using lexical cast.

检查字符串是否从另一个字符串开始,然后获取第一个字符串的子字符串('slice'),并使用lexical cast将其转换为字符串。