Java - 将整数转换为字符串[duplicate]

本文翻译自:Java - Convert integer to string [duplicate]

Given a number: 给出一个数字:

int number = 1234;

Which would be the "best" way to convert this to a string: 这将是将其转换为字符串的“最佳”方式:

String stringNumber = "1234";

I have tried searching (googling) for an answer but no many seemed "trustworthy". 我曾尝试搜索(谷歌搜索)一个答案,但没有多少似乎“值得信赖”。


#1楼

参考:https://stackoom.com/question/LHCy/Java-将整数转换为字符串-duplicate


#2楼

One that I use often: 我经常使用的一个:

 Integer.parseInt("1234");

Point is, there are plenty of ways to do this, all equally valid. 重点是,有很多方法可以做到这一点,所有这些都同样有效。 As to which is most optimum/efficient, you'd have to ask someone else. 至于哪个是最优/最有效的,你必须问别人。


#3楼

The way I know how to convert an integer into a string is by using the following code: 我知道如何将整数转换为字符串的方式是使用以下代码:

Integer.toString(int);

and

String.valueOf(int);

If you had an integer i, and a string s, then the following would apply: 如果您有一个整数i和一个字符串s,则以下内容适用:

int i;
String s = Integer.toString(i); or
String s = String.valueOf(i);

If you wanted to convert a string "s" into an integer "i", then the following would work: 如果您想将字符串“s”转换为整数“i”,那么以下内容将起作用:

i = Integer.valueOf(s).intValue();

#4楼

This is the method which i used to convert the integer to string.Correct me if i did wrong. 这是我用来将整数转换为string的方法。如果我做错了,请更正我。

/**
 * @param a
 * @return
 */
private String convertToString(int a) {

    int c;
    char m;
    StringBuilder ans = new StringBuilder();
    // convert the String to int
    while (a > 0) {
        c = a % 10;
        a = a / 10;
        m = (char) ('0' + c);
        ans.append(m);
    }
    return ans.reverse().toString();
}

#5楼

Always use either String.valueOf(number) or Integer.toString(number) . 始终使用String.valueOf(number)Integer.toString(number)

Using "" + number is an overhead and does the following: 使用“”+数字是一种开销并执行以下操作:

StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(number);
return sb.toString();

#6楼

There are multiple ways: 有多种方式:

  • String.valueOf(number) (my preference) String.valueOf(number) (我的偏好)
  • "" + number (I don't know how the compiler handles it, perhaps it is as efficient as the above) "" + number (我不知道编译器如何处理它,也许它与上面一样有效)
  • Integer.toString(number)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值