简体   繁体   English

在 C++ 中,如何从字符串中获取接下来的几个字符?

[英]In c++, how can I grab the next few characters from a string?

My goal is to grab a specific part of a very large number and concatenate that part with another number, then continue.我的目标是获取一个非常大的数字的特定部分并将该部分与另一个数字连接起来,然后继续。 Since integers only go so high, I have a string of the number.由于整数只有这么高,我有一个数字字符串。 I do NOT know what this number could be, so I can't input it in myself.我不知道这个数字可能是什么,所以我不能自己输入。 I can use substr for the first part, but I am stuck shortly after.我可以在第一部分使用 substr,但不久之后我就卡住了。

An example一个例子

"435509590420924949" “435509590420924949”

I want to take the first 5 characters out, convert to integer, do my own calculation to them, then concatenate them with the rest of the string.我想取出前 5 个字符,转换为整数,对它们进行自己的计算,然后将它们与字符串的其余部分连接起来。 So I will take 43550 out, do formula to get 49, then add 49 to another 5 in a row after the original string "95904" so the new answer will be "4995904".所以我将把 43550 取出来,做公式得到 49,然后在原始字符串“95904”之后连续将 49 添加到另一个 5,所以新的答案将是“4995904”。

This is my code for the first part I made up,这是我编写的第一部分的代码,

string temp;
int number;

temp = data.substr(0, 5);
number = atoi(temp.c_str());

This grabs the first first characters in the strings, converts to integers where I can calculate it, but I don't know how to grab the next 5 of the long string.这会抓取字符串中的第一个字符,转换为我可以计算的整数,但我不知道如何抓取长字符串的下 5 个字符。

You can get the length of the string, so something like:您可以获得字符串的长度,例如:

std::size_t startIndex = 0;
std::size_t blockLength = 5;
std::size_t length = data.length();
while(startIndex < length)
{
    std::string temp = data.substr(startIndex, blockLength);
    // do something with temp
    startIndex += blockLength;
    // TODO: this will skip the last "block" if it is < blockLength,
    // so you need to modify it a bit for this case.
}

You can use loops.您可以使用循环。 For example:例如:

std::size_t subStrSize = 5;
for (std::size_t k = 0; k < data.size(); k+=subStrSize) {
    std::size_t h = std::min(k + subStrSize - 1, data.size() - 1);
    int number = 0;
    for (std::size_t l = k; l <= h; ++l) 
        number = number * 10 + data[l] - '0';
    //-- Some work with number --
}

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

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