本文翻译自:Java - Convert integer to string [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
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)