我想使用 C++ 选择字符串的前 8 个字符。现在我创建一个 8 个字符长的临时字符串,并用另一个字符串的前 8 个字符填充它。
但是,如果另一个字符串不是 8 个字符长,则会留下不需要的空格。
string message = " ";
const char * word = holder.c_str();
for(int i = 0; i<message.length(); i++)
message[i] = word[i];
如果
word
是 "123456789abc"
,则此代码可以正常工作并且 message
包含 "12345678"
。
但是,如果
word
更短,例如 "1234"
,消息最终会变成 "1234 "
如何选择字符串的前 8 个字符,或者如果字符串短于 8 个字符,则选择整个字符串?
只需使用
std::string::substr
:
std::string str = "123456789abc";
std::string first_eight = str.substr(0, 8);
只需在字符串上调用 resize 即可。
如果我理解正确,你就写吧
std::string message = holder.substr( 0, 8 );
J如果您需要从字符数组中获取字符,那么您可以编写例如
const char *s = "Some string";
std::string message( s, std::min<size_t>( 8, std::strlen( s ) );
或者你可以使用这个:
#include <climits>
cin.ignore(numeric_limits<streamsize>::max(), '\n');
如果最大值为 8,它将停在那里。但你必须设置
const char * word = holder.c_str();
到8。我相信你可以通过写
来做到这一点 const int SIZE = 9;
char * word = holder.c_str();
让我知道这是否有效。
如果它们在任何时候触及空格,它只会读取到该空格。
您可以使用“%.xs”,如下所示。
char str[] = "Hello";
char target[9] = " ";
sprintf(target, "%.8s", str);
if(strlen(str) < 8)
target[strlen(str)]=' ';
printf("%s.", target);
char* messageBefore = "12345678asdfg"
int length = strlen(messageBefore);
char* messageAfter = new char[length];
for(int index = 0; index < length; index++)
{
char beforeLetter = messageBefore[index];
// 48 is the char code for 0 and
if(beforeLetter >= 48 && beforeLetter <= 57)
{
messageAfter[index] = beforeLetter;
}
else
{
messageAfter[index] = ' ';
}
}
这将创建一个适当大小的字符数组,并传输每个数字字符(0-9)并用空格替换非数字。这听起来像是您正在寻找的东西。
鉴于其他人根据您的问题进行的解释,您可以轻松修改上述方法,为您提供仅包含数字部分的结果字符串。
类似:
int length = strlen(messageBefore);
int numericLength = 0;
while(numericLength < length &&
messageBefore[numericLength] >= 48 &&
messageBefore[numericLength] <= 57)
{
numericLength++;
}
然后在前面的逻辑中使用
numericLength
代替length
,你将得到第一组数字字符。
希望这有帮助!