获取char数组的一部分

Cur*_*raw 11 c++ arrays char

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

是否可以从char数组中获取一组字符?抛弃一些伪代码:

char arry[20] = "hello world!";
char part[10] = arry[0-4];
printf(part);
Run Code Online (Sandbox Code Playgroud)

输出:

hello
Run Code Online (Sandbox Code Playgroud)

那么,我可以从这样的数组中获取一段字符而不循环并获取char-by-char或转换为字符串以便我可以使用substr()吗?

Oli*_*rth 15

简而言之,没有.C风格的"字符串"根本不起作用.您将不得不使用手动循环,或者strncpy()通过C++ std::string功能来完成.鉴于您使用的是C++,您可以使用C++字符串完成所有操作!

边注

碰巧,对于您的特定示例应用程序,您只需通过以下功能提供的功能即可实现此目的printf():

printf("%.5s\n", arry);
Run Code Online (Sandbox Code Playgroud)


Jer*_*ock 15

您可以使用memcpy(或strncpy)获取子字符串:

memcpy(part, arry + 5 /* Offset */, 3 /* Length */);
part[3] = 0; /* Add terminator */
Run Code Online (Sandbox Code Playgroud)

在代码的另一个方面,请注意,printf(str)如果str包含不受信任的输入,则可能导致格式字符串漏洞.


Moo*_*ice 5

正如Oli所说,您需要使用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;
Run Code Online (Sandbox Code Playgroud)