Get part of a char array(获取字符数组的一部分)
问题描述
我觉得这是一个非常愚蠢的问题,但我似乎无法在任何地方找到答案!
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);
这篇关于获取字符数组的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取字符数组的一部分
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
