String.length woes [英] String.length woes
问题描述
编辑:解决方案必须编译Microsoft Visual Studio 2012.
Solutions must compile against Microsoft Visual Studio 2012.
我想使用已知的字符串长度来声明另一个相同长度的字符串。
I want to use a known string length to declare another string of the same length.
推理是第二个字符串将作为对第一个字符串进行操作的容器,对于第一个字符串必须是非易失性的。
The reasoning is the second string will act as a container for operation done to the first string which must be non volatile with regards to it.
例
const string messy "a bunch of letters";
string dostuff(string sentence) {
string organised NNN????? // Idk, just needs the same size.
for ( x = 0; x < NNN?; x++) {
organised[x] = sentence[x]++; // Doesn't matter what this does.
}
}
在上述两种情况下,声明和退出条件,NNN?
In both cases above, the declaration and the exit condition, the NNN? stands for the length of 'messy'.
如何在编译时发现长度?
How do I discover the length at compile time?
推荐答案
std :: string
有两个构造函数。
第一个是复制构造函数:
The first, a copy constructor:
string organised(sentence);
第二个是一个构造函数,它接受一个字符和一个计数。您可以使用临时字符初始化字符串。
The second, a constructor which takes a character and a count. You could initialize a string with a temporary character.
string organised(sentence.length(), '_');
或者,您可以:
- 使用空字符串,并在其后添加(
+ =
)文本,或 - 使用
std :: stringstream
同样的目的。
- Use an empty string and append (
+=
) text to it as you go along, or - Use a
std::stringstream
for the same purpose.
。
>总的来说,如果长度已知,我宁愿选择复制构造函数。
Overall, I would prefer the copy constructor if the length is known.
这篇关于String.length woes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!