Skip to content

Files

Latest commit

ed2b32f · Oct 12, 2019

History

History
146 lines (104 loc) · 3.41 KB

File metadata and controls

146 lines (104 loc) · 3.41 KB

Java 程序:intString的转换

原文: https://beginnersbook.com/2015/05/java-int-to-string/

在本指南中,我们将学习如何在 Java 中将int转换为字符串。我们可以使用String.valueOf()Integer.toString()方法将int转换为String。我们也可以使用String.format()方法进行转换。

1. 使用String.valueOf()int转换为String

String.valueOf(int i)方法将整数值作为参数,并返回表示int参数的字符串。

方法签名

public static String valueOf(int i

参数

i - 需要转换为字符串的整数

返回

表示整数参数的字符串

使用String.valueOf()int转换为String

public class JavaExample {
   public static void main(String args[]) {
	int ivar = 111;
	String str = String.valueOf(ivar);
	System.out.println("String is: "+str); 
	//output is: 555111 because the str is a string 
	//and the + would concatenate the 555 and str
	System.out.println(555+str);
   }
}

输出:

Java Int to String conversion

2. 使用Integer.toString()int转换为String

Integer.toString(int i)方法与String.valueOf(int i)方法的作用相同。它属于Integer类,并将指定的整数值转换为String。例如如果传递的值是 101,那么返回的字符串值将是"101"

方法签名

public static String toString(int i

参数

i - 需要转换的整数

返回

表示整数i的字符串。

示例:

int ivar2 = 200;
String str2 = Integer.toString(ivar2);

使用Integer.toString()intString转换

public class Example {
   public static void main(String args[]) {
        int ivar = 111;
	String str = Integer.toString(ivar);
	System.out.println("String is: "+str);
	//output is: 555111 because the str is a string 
	//and the + would concatenate the 555 and str
	System.out.println(555+str);

	//output is: 666 because ivar is int value and the
        //+ would perform the addition of 555 and ivar
	System.out.println(555+ivar);
   }
}

输出:

String is: 111
555111
666

示例:将int转换为String

该程序演示了如何使用上述方法(String.valueOf()Integer.toString())。这里我们有两个整数变量,我们使用String.valueOf(int i)方法转换其中一个,使用Integer.toString(int i)方法转换其中一个。

public class IntToString {
    public static void main(String[] args) {

        /* Method 1: using valueOf() method
         * of String class.
         */
        int ivar = 111;
        String str = String.valueOf(ivar);
        System.out.println("String is: "+str);

        /* Method 2: using toString() method 
         * of Integer class
         */
        int ivar2 = 200;
        String str2 = Integer.toString(ivar2);
        System.out.println("String2 is: "+str2);
    }
}

输出:

String is: 111
String2 is: 200

3. 用于转换的String.format()方法

public class JavaExample{  
   public static void main(String args[]){  
	int num = 99;  
	String str = String.format("%d",num);  
	System.out.println("hello"+str);  
   }
}

输出:

hello99