将字符串转换为 int 然后再转换回字符串 [英] Converting string to int and then back to string

查看:51
本文介绍了将字符串转换为 int 然后再转换回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的字符串变量转换为整数以向它添加一个值 (+1),但我得到的结果是:

I am trying to convert my string variable to an integer to add a value (+1) to it but the result I get is:

1111

事实上,当我将它重新转换为字符串时,我总共应该得到 4 个.

Infact I should be getting a total of 4 when I reconvert it to string.

我做错了什么?

public string str_Val = "1";

void Update () {
if (str_Val  != "5") {
      str_Val  = int.Parse (str_Val + 1).ToString ();
   }
}

推荐答案

关键在于操作的优先级:

It's all about the priority of the actions:

int.Parse (str_Val + 1)

在上面的行中,加法发生在 str_Val + 1 输出 11,111,111 等.

In the row above first the addition happens str_Val + 1 outputing 11,111,111 etc.

然后解析发生将 "11" 更改为 11

Then the parsing occurs changing "11" to 11

然后字符串发生将 11 更改为 "11"

Then to string occurs changing 11 to "11"

因此将您的代码更改为

str_Val  = (int.Parse(str_Val)+1).ToString();

这将首先将字符串转换为 int,然后添加两个整数,最后再次将整数转换为字符串.

This will first convert the string to int, then add two integers and finally convert the integer to string again.

这篇关于将字符串转换为 int 然后再转换回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆