仅选择字符串C ++中的前几个字符 [英] Selecting only the first few characters in a string C++
问题描述
我想使用C ++选择字符串的前8个字符。现在,我创建一个长度为8个字符的临时字符串,并用另一个字符串的前8个字符填充它。
I want to select the first 8 characters of a string using C++. Right now I create a temporary string which is 8 characters long, and fill it with the first 8 characters of another string.
但是,如果另一个字符串不是8个字符
However, if the other string is not 8 characters long, I am left with unwanted whitespace.
string message = " ";
const char * word = holder.c_str();
for(int i = 0; i<message.length(); i++)
message[i] = word[i];
如果单词
是 123456789abc
,此代码可以正常工作,并且消息
包含 12345678
。
If word
is "123456789abc"
, this code works correctly and message
contains "12345678"
.
但是,如果单词
较短,则类似于 1234
,消息最终显示为 1234
However, if word
is shorter, something like "1234"
, message ends up being "1234 "
如何选择字符串的前八个字符,或者如果整个字符串少于8个字符,则整个字符串?
How can I select either the first eight characters of a string, or the entire string if it is shorter than 8 characters?
推荐答案
只需使用 std :: string :: substr
:
std::string str = "123456789abc";
std::string first_eight = str.substr(0, 8);
这篇关于仅选择字符串C ++中的前几个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!