String s = "21-1 + 2";怎么转换成数字
时间: 2023-04-02 19:04:52 浏览: 71
可以使用以下代码将字符串转换为数字:
int num = Integer.parseInt(s.replaceAll("\\D", ""));
其中,replaceAll("\\D", "")表示将字符串中的非数字字符替换为空字符串,即去掉空格和减号。然后使用Integer.parseInt()方法将字符串转换为整数。
相关问题
String s = "(1+2)*3/4-3/(1-1)" java解析结果
这个表达式的解析结果是:-2。
具体的解析过程如下:
1. 首先,将表达式中所有的空格去除,得到s="(1+2)*3/4-3/(1-1)"。
2. 接下来,我们需要将中缀表达式转换为后缀表达式。具体的转换过程可以使用栈来实现。我们从左到右遍历中缀表达式,如果遇到数字,直接输出;如果遇到运算符,判断其与栈顶运算符的优先级,如果栈顶运算符优先级高于或等于该运算符,则弹出栈顶运算符并输出,然后将该运算符压入栈中。重复上述过程,直到遍历完整个中缀表达式。最后,将栈中所有运算符依次弹出并输出。
根据这个转换规则,可以将中缀表达式 "(1+2)*3/4-3/(1-1)" 转换为后缀表达式 "1 2 + 3 * 4 / 3 1 1 - / -"。
3. 接下来,我们需要计算后缀表达式的值。同样可以使用栈来实现。从左到右遍历后缀表达式,如果遇到数字,将其压入栈中;如果遇到运算符,则弹出栈顶的两个数字进行运算,并将运算结果压入栈中。重复上述过程,直到遍历完整个后缀表达式。最后,栈中只剩下一个数字,就是整个表达式的计算结果。
根据这个计算规则,可以得到后缀表达式 "1 2 + 3 * 4 / 3 1 1 - / -" 的计算结果为 -2。
#include <stdio.h>#include <string.h>void replace(char* str) { int len = strlen(str); int i, count; char prev = str[0]; count = 1; for (i = 1; i < len; i++) { if (str[i] == prev) { count++; } else { if (count > 1) { str[i - count] = 'X'; str[i - count + 1] = count + '0'; memmove(str + i - count + 2, str + i, len - i + 1); len -= count - 2; i -= count - 2; } prev = str[i]; count = 1; } } if (count > 1) { str[i - count] = 'X'; str[i - count + 1] = count + '0'; len -= count - 2; } str[len] = '\0';}int main() { char str[100]; printf("Input a string: "); fgets(str, 100, stdin); replace(str); printf("Result: %s", str); return 0;}中的 str[i - count + 1] = count + '0';作用
在这段代码中,str[i - count + 1] = count + '0'; 的作用是将连续出现的相同字符的数量转换为字符类型并存储到字符串中。由于 '0' 的 ASCII 值为 48,所以将数字 count 转换为字符类型时需要加上 48(即 '0' 的 ASCII 值),这样才能正确地将数字转换为字符。例如,如果 count 的值为 2,则 '2' 的 ASCII 值为 50,因此 str[i - count + 1] 的值将被赋为 '2'。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)