Java 整数到字符串的转换方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3802684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Integer to String conversion methods
提问by Selva
What are the alternative methods for converting and integer to a string?
将整数转换为字符串的替代方法是什么?
采纳答案by sfaiz
Integer.toString(your_int_value);
or
或者
your_int_value+"";
and, of course, Java Docs should be best friend in this case.
当然,在这种情况下,Java Docs 应该是最好的朋友。
回答by Thomas L?tzer
String one = Integer.toString(1);
回答by fredley
String myString = Integer.toString(myInt);
回答by Emil
String.valueOf(anyInt);
回答by Micha? Niklas
There is Integer.toString()
or you can use string concatenation where 1st operand is string (even empty): String snr = "" + nr;
. This can be useful if you want to add more items to String variable.
有Integer.toString()
或者您可以使用字符串连接,其中第一个操作数是字符串(甚至为空):String snr = "" + nr;
。如果您想向 String 变量添加更多项目,这会很有用。
回答by Sean Patrick Floyd
Here are all the different versions:
以下是所有不同的版本:
a) Convert an Integer to a String
a) 将整数转换为字符串
Integer one = Integer.valueOf(1);
String oneAsString = one.toString();
b) Convert an int to a String
b) 将 int 转换为 String
int one = 1;
String oneAsString = String.valueOf(one);
c) Convert a String to an Integer
c) 将字符串转换为整数
String oneAsString = "1";
Integer one = Integer.valueOf(oneAsString);
d) Convert a String to an int
d) 将字符串转换为整数
String oneAsString = "1";
int one = Integer.parseInt(oneAsString);
There is also a page in the Sun Java tutorial called Converting between Numbers and Strings.
Sun Java 教程中还有一个页面叫做Converting between Numbers and Strings。
回答by Sean Patrick Floyd
You can use String.valueOf(thenumber)
for conversion. But if you plan to add another word converting is not nessesary. You can have something like this:String string = "Number: " + 1
This will make the string equal Number: 1.
您可以String.valueOf(thenumber)
用于转换。但是,如果您打算添加另一个单词,则转换不是必需的。你可以有这样的东西:String string = "Number: " + 1
这将使字符串等于 Number: 1。