在字符串中设置一个等于 int + "," 的某个字母
set a certain letter in a string equal to an int + ","
我目前正在编写一个函数,用相应的数字加上","替换一行中的字母。我当前的代码是:
std::string letterToNumber(std::string message) {
std::string::iterator iter;
toUpper(message);
for (iter = message.begin(); iter != message.end(); ++iter) {
for (int i = 0; i < alphabetSize; ++i) {
if (*iter == alphabet[i]) {
// Problem here
}
}
}
return message;
}
(toUpper是我自己的函数)。我不太确定如何将字符串中的当前字母分配给数字+逗号。起初我尝试只为特定字母分配一个数字,但我意识到我需要一个分隔符,所以我决定使用逗号。
我想您要实现的是:
std::string letterToNumber(std::string input) {
toUpper(input);
std::stringstream output;
std::string::iterator it;
for (it = input.begin(); it != input.end(); ++it) {
if (input.begin() != it) {
output << ",";
}
int letterIndex = static_cast<int>(*it) - 'A';
output << letterIndex;
}
return output.str();
}
- 对我来说,构建一个新字符串而不是尝试编辑现有字符串看起来更简单、更高效,因为由于字母 (1 个字符) 映射到多个字符,因此您的初始字符串需要几个低效的副本和重新分配。
- 若要从字符转换为其索引,可以使用 ASCII 字符自然有序且连续的事实。
- 您可以为非字母字符添加保护,例如数字和大多数标点符号将返回负索引
相关文章:
- 在类 (C++) 之外设置 const int 成员变量
- 类中的 C++ int 被设置为值,似乎不知从何而来
- 查找不在标准中的第一个值::设置<int>最小-最大值
- Qt 原子 int 获取并立即设置
- 如何检查 int 中是否恰好设置了一位?
- 无法从JNI设置Java Int数组字段
- 将标准:设置为<int> jintArray
- C++:无法在按位函数后将 int 类型设置为非标量
- 在循环中设置指向 int 值的指针
- 错误C4430:丢失类型指定词 - 假设INT.注意:C 不支持对我的构造函数的默认设置
- C++:Unordered_map.template(char,int)未设置所需的值
- 无法使用 pair<int、int> 作为 STL 中设置C++键
- 使用强制转换和设置填充将 int 值更改为时间
- 如何将数组的一部分从 int 转换为浮点数并将值设置为另外两个数组
- 在字符串中设置一个等于 int + "," 的某个字母
- 如何在C 中的结构内设置一个int数组
- 将 std::vector<int> 设置为一个范围
- 如果我将 int 设置为等于 2 个最大整数的总和会发生什么
- 如何在C++中将 const int 设置为最大值
- 转换 map<int C++,请将<int>>设置为 map<int, 矢量<int>>