c++计算字符串中的数字

C++ Counting Numbers in a String

本文关键字:数字 字符串 计算 c++      更新时间:2023-10-16

给定一个字符串,如"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));