简体   繁体   English

C ++:char test [100]与数组 <char, 100> vs字符串

[英]C++: char test[100] vs array<char, 100> vs string

If I have a string that I know will be of constant length, what should I use? 如果我知道一个长度固定的字符串,应该使用什么?

char test[100]
std::array<char, 100> test
std::string test

Thanks! 谢谢!

The answer is in the question: 答案在以下问题中:

If I have a string ... 如果我有一个字符串 ...

If you have a string, use std::string . 如果您有字符串,请使用std::string Unless you have very specific requirements that you have not mentioned. 除非您有没有提到的非常具体的要求。

In C++ a string should be declared as a string instance. 在C ++中,应将字符串声明为string实例。 But if you need it to be constant then declare it as a const string and initialize it properly. 但是,如果您需要它为常量,则将其声明为const string并正确初始化。

char test[100] is not a string but a C-array of 100 chars (that can be used to build a C++ string if needed). char test[100]不是字符串,而是100个字符的C数组(可根据需要用于构建C ++字符串)。

std::array<char,100> test is just a C++ array of hundred chars, nothing related to string. std::array<char,100> test只是一个由数百个字符组成的C ++数组,与字符串无关。

Whether you know it will be constant length or not, it's pretty much always going to be recommended that you use std::string . 无论您知道它是否为恒定长度,几乎总是建议您使用std::string Having the string be contained in an actual string object enables you to query the string for metainformation (length, for example) and integrate better with C++ functionality for handling strings. 将字符串包含在实际的字符串对象中,使您可以查询字符串的元信息(例如长度),并更好地与C ++功能集成以处理字符串。 If ensuring that the string /cannot/ be more than 100 characters is super vital to you, you might find 如果确保字符串/ cannot /不能超过100个字符对您来说至关重要,那么您可能会发现

std::array<char, 100>

to be valuable, but I can't think of any situations where you'd rather have that functionality than just using a string. 是有价值的,但是我想不出除了使用字符串之外,还希望具有该功能的任何情况。

Unless you have a reason otherwise you should prefer a std::string . 除非有其他原因,否则您应该首选std::string Not only does this say that the data is a string but you get all of the nice string functions as well. 这不仅表明数据是一个字符串,而且还获得了所有不错的字符串函数。

You also get the benefit that if you decide to change the code and allow variable/larger sized strings then you don' need to change anything as std::string will scale 您还获得了好处,如果您决定更改代码并允许使用可变的/较大的字符串,则无需更改任何内容,因为std::string可以缩放

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM