获取字符数组的一部分

2022-01-12 00:00:00 arrays char c++

我觉得这是一个非常愚蠢的问题,但我似乎无法在任何地方找到答案!

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);

输出:

hello

那么,我可以从这样的数组中获取一段字符,而无需循环并逐个字符地获取它们或转换为字符串,以便我可以使用 substr() 吗?

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()?

推荐答案

总之,没有.C 风格的字符串"根本不能那样工作.您要么必须使用手动循环,要么使用 strncpy(),或者通过 C++ std::string 功能来实现.既然你在 C++ 中,你也可以用 C++ 字符串来做任何事情!

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!

旁注

碰巧,对于您的特定示例应用程序,您可以通过 printf() 提供的功能简单地实现这一点:

As it happens, for your particular example application, you can achieve this simply via the functionality offered by printf():

printf("%.5s
", arry);

相关文章