在c++中,如何从字符串中删除字母,并从字母中向int添加一个数字

In c++ how to remove letter from a string and add a number to int from the letter

本文关键字:添加 数字 一个 int 字符串 删除 c++      更新时间:2023-10-16

我要做的是使用一个类似于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的擦除方法。