C++ 从字符串中给定结束索引的字符串中复制子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2796726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:43:16  来源:igfitidea点击:

copying a substring from a string given end index in string

c++

提问by boom

How can I copy a substring from a given string with start and end index or giving the start index and length of the string are given.

如何从给定的字符串中复制子字符串的起始和结束索引或给出字符串的起始索引和长度。

回答by jamesdlin

From a std::string, std::string::substrwill create a new std::stringfrom an existing one given a start index and a length. It should be trivial to determine the necessary length given the end index. (If the end index is inclusive instead of exclusive, some extra care should be taken to ensure that it is a valid index into the string.)

From a std::string,std::string::substrstd::string根据给定的起始索引和长度从现有的创建一个新的。给定结束索引确定必要的长度应该是微不足道的。(如果结束索引是包含而不是排他的,则应格外小心以确保它是字符串中的有效索引。)

If you're trying to create a substring from a C-style string (a NUL-terminated chararray), then you can use the std::string(const char* s, size_t n)constructor. For example:

如果您尝试从 C 样式字符串(以 NUL 结尾的char数组)创建子字符串,则可以使用std::string(const char* s, size_t n)构造函数。例如:

const char* s = "hello world!";
size_t start = 3;
size_t end = 6; // Assume this is an exclusive bound.

std::string substring(s + start, end - start);

Unlike std::string::substr, the std::string(const char* s, size_t n)constructor can read past the end of the input string, so in this case you also should verify first that the end index is valid.

与 不同std::string::substrstd::string(const char* s, size_t n)构造函数可以读取输入字符串的末尾,因此在这种情况下,您还应该首先验证结束索引是否有效。

回答by Alex Martelli

std::string thesub = thestring.substr(start, length);

or

或者

std::string thesub = thestring.substr(start, end-start+1);

assuming you want the endth character to be included in the substring.

假设您希望将end第 th 个字符包含在子字符串中。

回答by Raviprakash

You can use substrmethod od std:string class.

您可以使用substr方法 od std:string 类。