我試圖用數字 5 替換 W(在本例中)。但是,當我嘗試時,我只得到 5 的 ascii 值來替換 W,而不是數字 5 本身。我將如何解決這個問題?
注意:這是一個較長項目的縮短示例。我需要訪問 nums[1] 中的數字。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nums[3] {4,5,6};
string str = "HELLO WORLD";
cout << str << endl;
str[6] = nums[1];
cout << str << endl;
return 0;
}
輸出:你好
世界
你好♣ORLD
您可以將數字轉換為 ASCII 字符:(char c = '0' + 5
給您'5'
)。
這是您修復的代碼:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nums[3] {4,5,6};
string str = "HELLO WORLD";
cout << str << endl;
str[6] = '0' + nums[1];
cout << str << endl;
return 0;
}
但是,如果您打算像標題所說的那樣插入整數,則必須執行以下操作:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nums[3] {4,15,6};
string str = "HELLO WORLD";
cout << str << endl;
// str = str.substr(0, 6) + std::to_string(nums[1]) + str.substr(7);
str.replace(6, 1, std::to_string(nums[1])); // as Remy Lebeau has mentioned in the comments
cout << str << endl;
return 0;
}
(UPD:它相當於std::string::replace
)這是一個更複雜的版本,它嘗試使用現有容量:
#include <iostream>
#include <string>
#include <algorithm>
// don't ever do it with std
// using namespace std;
size_t count_digits(int num)
{
int digits = 0;
do {
num /= 10;
digits++;
} while (num);
return digits;
}
void insert_number(std::string& str, size_t indx, int num)
{
const size_t digits = count_digits(num),
oldSize = str.size();
// insert will reallocate only if capacity is not enough
str.insert(str.size(), digits - 1, '0');
// move the end of string right by rotating (rewriting characters)
auto iterBegin = std::next(str.begin(), indx),
iterNext = std::next(str.begin(), oldSize);
std::rotate(iterBegin, iterNext, str.end());
// write our string from integer to the designated space
const auto &strInteger = std::to_string(num);
for (size_t iStr = indx, iInt = 0; iInt != strInteger.size(); ++iInt, ++iStr)
str[iStr] = strInteger[iInt];
}
int main()
{
int nums[3] {4, 48152342, 6};
std::string str = "HELLO WORLD LOOOOONG STRIIING";
str.reserve(str.capacity() + 20); // strings don't preallocate more space after construction
std::cout << str << std::endl;
std::cout << "capacity before: " << str.capacity() << std::endl;
insert_number(str, 6, nums[1]);
std::cout << str << std::endl;
std::cout << "capacity after: " << str.capacity() << std::endl;
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句