将一个字符串缩放到另一个字符串的更大长度
Scale up a string to another string with higher length
我需要将长度为6的字符串"110021"缩放为长度为12的字符串
所以可能方法应该返回类似"111100002211"
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; }
}
注意,当新长度小于旧长度时,这个semi会断裂。(它会将第一个new_length字符添加到字符串中,然后停止。)
下面是一些几乎正确的代码。我故意引入了一个小bug,这样我就不会完全完成你的作业。高级C或c++程序员会立即发现bug,因为它已经有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;
}
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;
}
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 我如何通过引用将 c++ 字符串分配给另一个字符串
- 使用另一个字符串从字符串中删除空格
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何在使用 getch 后在另一个字符串的末尾连接一个字符串
- 如何在另一个字符串的x位置插入一个字符串?
- 从 C 字符串构造 std::string 与从另一个 std::string 构造 std::string 不一致
- C++:递归地将字符串中一个字母的所有实例替换为另一个字母
- 在另一个字符串中插入文件扩展名之前的字符串
- 使用C++将一个字符串替换为另一个字符串
- 将字符从一个字符串简单分配到另一个字符串不起作用
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将字符串中的单个单词替换为另一个单词
- 将文本流中一个字符串的所有匹配项替换为另一个字符串
- 无法将字符串用作另一个类的参数
- 另一个字符串文字,UDL 迷宫
- 在给定字符串上使用 tolower() 和 isalpha() 并将其输出设置为另一个字符串
- 如何使用循环从另一个字符串创建一个没有空格的新字符串