C++ 获取字符数组的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4777207/
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
Get part of a char array
提问by Curlystraw
I feel like this is a really silly question, but I can't seem to find an answer anywhere!
我觉得这是一个非常愚蠢的问题,但我似乎无法在任何地方找到答案!
Is it possible to get a group of chars from a char array? to throw down some pseudo-code:
是否可以从字符数组中获取一组字符?扔掉一些伪代码:
char arry[20] = "hello world!";
char part[10] = arry[0-4];
printf(part);
output:
输出:
hello
So, can I get a segment of chars from an array like this without looping and getting them char-by-char or converting to strings so I can use substr()?
那么,我是否可以从这样的数组中获取一段字符而不需要循环并逐个字符地获取它们或转换为字符串以便我可以使用 substr()?
回答by Oliver Charlesworth
In short, no. C-style "strings" simply don't work that way. You will either have to use a manual loop, or strncpy()
, or do it via C++ std::string
functionality. Given that you're in C++, you may as well do everything with C++ strings!
简而言之,没有。C 风格的“字符串”根本不能那样工作。您将不得不使用手动循环,或者strncpy()
,或者通过 C++std::string
功能来完成。鉴于您使用的是 C++,您也可以使用 C++ 字符串来做所有事情!
Side-note
边注
As it happens, for your particular example application, you can achieve this simply via the functionality offered by printf()
:
碰巧的是,对于您的特定示例应用程序,您可以通过以下提供的功能轻松实现这一点printf()
:
printf("%.5s\n", arry);
回答by Jeremiah Willcock
You could use memcpy
(or strncpy
) to get a substring:
您可以使用memcpy
(或strncpy
) 来获取子字符串:
memcpy(part, arry + 5 /* Offset */, 3 /* Length */);
part[3] = 0; /* Add terminator */
On another aspect of your code, note that doing printf(str)
can lead to format string vulnerabilities if str
contains untrusted input.
在代码的另一方面,请注意,printf(str)
如果str
包含不受信任的输入,这样做可能会导致格式字符串漏洞。
回答by Moo-Juice
As Oli said, you'd need to use C++ std::string
functionality. In your example:
正如奥利所说,您需要使用 C++std::string
功能。在你的例子中:
std::string hello("Hello World!");
std::string part(hello.substr(0, 5)); // note it's <start>, <length>, so not '0-4'
std::cout << part;
回答by Keith
Well, you do mention the two obvious approaches. The only thing I can think of would be to define your own substring type to work off character arrays:
好吧,您确实提到了两种明显的方法。我唯一能想到的就是定义你自己的子字符串类型来处理字符数组:
struct SubArray
{
SubArray(const char* a, unsigned s, unsigned e)
:arrayOwnedElseWhere_(a),
start_(s),
end_(e)
{}
const char* arrayOwnedElseWhere_;
unsigned start_;
unsigned end_;
void print()
{
printf_s("%.*s\n", end_ - start_ + 1, arrayOwnedElseWhere_ + start_);
}
};