我需要将长度为6的字符串“110021”扩展为长度为12的字符串
所以方法可能应该返回类似:“111100002211”
答案 0 :(得分:3)
std::string original = "110021";
std::string result;
size_t new_length = 12;
// need (multiple) copies of each char, plus an extra one of each of the first
// (remainder) chars
size_t multiple = new_length / original.size();
size_t remainder = new_length % original.size();
// not strictly necessary, but since we already know the result's length...
result.reserve(new_length);
for (char c : original) {
result.append(multiple, c);
if (remainder) { result.append(1, c); --remainder; }
}
对于最后一部分,如果你还没有得到像样的C ++ 11支持:
for (std::string::iterator it = original.begin(); it != original.end(); ++it) {
result.append(multiple, *it);
if (remainder) { result.append(1, *it); --remainder; }
}
请注意,当新长度小于旧长度时,此半断开。 (它会将第一个new_length字符添加到字符串中,然后停止。)如果您想要某些行为,您应该更清楚地指定一些内容。
答案 1 :(得分:1)
这是一些几乎正确的代码。我特意介绍了一个小虫子,所以我不完全做你的功课。高级C或C ++程序员会立即发现错误,因为它已经闻起来像一个bug。
#include <cassert>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <string>
using std::size_t;
using std::string;
/** a * b / c, rounded towards zero. */
size_t muldiv(size_t a, size_t b, size_t c) {
unsigned long long product = a * b;
assert(a == 0 || product / a == b);
return product / c;
}
string scale(const string &s, size_t new_length) {
string result;
for (size_t i = 0; i <= new_length; i++) {
size_t index = muldiv(i, s.length(), new_length);
result += s.at(index);
}
return result;
}
void assert_equals(const string &expected, const string &actual) {
if (expected != actual) {
std::cerr << "Expected \"" << expected << "\", got \"" << actual << "\".\n";
std::exit(EXIT_FAILURE);
}
}
void test_scale() {
assert_equals("111100002211", scale("110021", 12));
assert_equals("110021", scale("110021", 6));
assert_equals("102", scale("110021", 3));
assert_equals("1111222333444", scale("1234", 13));
}
int main() {
try {
test_scale();
} catch (std::exception &e) {
std::cerr << e.what() << "\n";
}
return 0;
}
答案 2 :(得分:0)
int main()
{
std::string x("110022");
std::string y;
unsigned int newLenght = 40; // for example
for (std::string::iterator it = x.begin(); it != x.end(); ++it)
{
for (unsigned int i = 0; i < newLenght / x.length(); i++)
{
y += *it;
}
}
std::cout << y << std::endl;
return 0;
}