在c++中,如何从字符串中删除字母,并从字母中向int添加一个数字
In c++ how to remove letter from a string and add a number to int from the letter
我要做的是使用一个类似于AABBCC的字符串作为字符串的值。我要做的是一个循环,它查看字符串变量中的第一个字母,删除第一个字母并根据数字向int变量添加一个数字。我想找的只是说说而已。
string LettertoNumber=AABBCC
环路
取LettertoNumber 中的第一个字母
删除第一个字母A
将1添加到int变量
当A不再是的第一个字母时结束循环
环路
将字母中的第一个字母取为数字B
删除第一个字母B
将2添加到int变量
当B不再是的第一个字母时结束循环
环路
将字母中的第一个字母记为编号C
删除第一个字母C
将3添加到int变量
当C不再是的第一个字母时结束循环
现在我可以找到如何使用int变量将数字相加。我找不到的是如何根据所说的内容从字符串中删除。我正在寻找一种我能理解的方法。
您不需要删除字母,只需遍历字符串并相应地更新总和即可:
string s;
cin >> s;
int sum = 0;
for (int i = 0; i < s.size();) {
do {
// as long as:
// 1. you are not at the end of the string
// and
// 2. there is a sequence of equal chars
// update your sum accordingly
sum += value_you_want_for(s[i]);
i++;
} while (i < s.size() && s[i - 1] == s[i])
}
cout << sum;
如果真的,真的想要删除字符,可以使用std::string
的擦除方法。
相关文章:
- 我需要知道如何在 c++ 中使用增量值添加到一定数字
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 在不添加进位的情况下添加数字的C++程序
- 将两个数字添加为链表
- C++:添加到输出中的不需要的数字
- 如何非常快速地将数字添加到 Vector 中的一系列元素中
- 如何在 c++ 中添加两个大的双精度数字
- 字符串添加数字 C++
- Arduino代码无法正确添加数字
- 如何从 while 循环中添加数字
- 在我的输出之前,我该如何添加数字
- C 如何结束一个段循环,该循环添加数字而不使用数字作为触发器来结束循环
- 无法理解为什么在添加数字后在末尾添加零
- C++输入文件添加数字
- 如何创建添加数字的模板函数
- 向字符串数组中的元素添加数字值
- 重载运算符>>并向字符串添加数字
- 如何在矩阵中添加数字以产生最小结果
- 在fstream中添加数字(c++)
- g++ -D选项添加数字1