c++计算字符串中的数字
C++ Counting Numbers in a String
给定一个字符串,如"121",我试图计算1和2的数量,然后返回字符串"2112"(因为有2个1和1个2)。我不确定问题在哪里在我的代码,但我得到荒谬的结果,如果有人能指出哪里出错,那将是伟大的。这是我到目前为止的代码:
现在可以用了,非常感谢。
string operate(string s)
{
string input = "121;
int count[10] = {0};
string answer;
for(int n = 0; n < input.length(); n++)
{
int a = (input[n]-'0');
count[a]++;
}
for(int n = 1; n < 10; n++)
{
if(count[n] > 0)
{
stringstream ss;
ss << count[n] << n;
answer.append(ss.str());
}
}
return answer;
}
这里有三个问题。首先,在使用内存之前没有初始化内存。这很简单:
int count[10]{}; //all 0
由于编译器支持的原因而失败,像这样的东西可以工作:
int count[10] = {0};
接下来,你正在越界访问数组:
int a = input[n];
count[a]++;
首先,将字符串中该字符的数值赋给a
。如果使用ASCII并且字符为'1'
,则该值为49。接下来,访问数组的元素a
。这里只有10个,但你可能要访问过这个。由于数字字符代码是连续的,只需减去0
以获得您正在寻找的整数形式的数字值:
int a = input[n] - '0';
count[a]++;
以'1'
为例,连续意味着'1'
比'0'
晚一个,因此'1' - '0'
为1。
最后,稍后将忽略数组的第一个元素。使第二个循环从0开始索引,而不是从1开始。
有了这个方法,我可以建议使用字典(用一些c++ 11来玩)吗?
std::string input = "12113412";
std::map<char, int> count; //map characters to counts
for (char c : input) //loop through each character in string
count[c]++; //this creates the element if it isn't
std::string result;
for (auto p : count) { //each value in map is a pair
result += std::to_string(p.second) += p.first;
}
std::cout << result;
输出:41221314
你的代码有多个问题。
首先,:
int count[10];
. .不会初始化这些值。它们将是随机的内存地址。你想要这个:
int count[10] = { 0 };
. .这使得数组中的所有项初始化为0。
同样,你只在数组中声明10个元素,但是这个:
int a = input[n];
. .在"121"(1 == 49 ASCII)的示例中,将"49"存储在变量a
中。然后你要这样做:
count[49]++; // Wrong.. there is no element 49
您似乎将数组用作某种Dictionary
,这不是。
把它改成这样:
int a = input[n] - 48;
count[a]++;
…工作。这是完整的输出:
std::string operate(std::string s)
{
int count[10] = { 0 };
string answer;
for(int n = 0; n < s.length(); n++)
{
int a = s[n] - 48;
count[a]++;
}
for(int n = 0; n < 10; n++)
{
if(count[n] > 0)
{
stringstream ss;
ss << count[n] << n;
answer.append(ss.str());
}
}
return answer;
}
. .返回输入为"121"的2112
。
分配给'a'的那一行应该如下所示:
int a=todigit(input[n]);
你当前所做的是分配ASCII值,这将导致缓冲区溢出
int a = input[n]?
输入[n]是一个字符,a将得到对应字符的ASCII码。对于您的示例,输入[0]返回49,这是字符"1"的ascii值。使用atoi将char转换为int就可以了。
你应该初始化count[10]。
memset(&count, 0, sizeof(count));
- 生成随机长度的数字字符串
- 如何在c ++中将大数字字符串转换为整数?
- 将非数字字符串存储为二进制整数
- Flex 词法分析器规则,对包含连字符和斜杠的字母数字字符串具有积极的前瞻断言
- 如何在C++中将数字字符串拆分为数组
- 总结数字字符串输入的最佳方法
- 如何将输入的数字字符串转换为 int 数组
- 如何获得两个数字字符串的总和-C
- 使用 C++ 替换 txt 文件中的文本数字字符串
- 如何有效地将数字字符串值分配给整数
- String Stream in C++ 解析单词和数字字符串
- c++将大型数字字符串映射到数字字符串范围
- 获取用数字字符串表示的树中的所有直接父级/子级
- 如何从 char 数组中提取数字字符串成员
- 比较两个字母数字字符串
- 有没有一种方法可以设置浮点变量=某个数字*字符串中的变量
- 使用矢量对字母数字字符串进行排序
- 正在分析未知类型的数字字符串
- 如何在c++中从一个科学数字字符串中修剪后面的零
- 无法将字符串数组中的数字字符串转换为浮点值