字符串与基本数据类型的转换

1.字符串转换为数字

java.lang中的Integer类调用其类方法public static int paeseInt(String s)可以将由“数字”字符组成的字符串,比如“876”转换为int数据类型,例如:

 int x;

 String s = "876";

 x = Integer.paeseInt(s);

 类似地,使用java.lang包中的Byte、Short、Long、Float、Double类调用相应的类方法

public static byte parseByte(String s) throws NumberFormatException 

public static short parseShort(String s) throws NumberFormatException 

public static long parseLong(String s) throws NumberFormatException 

public static double parseDouble(String s) throws NumberFormatException 

 2.可以使用下面的方法将数字转化为相应的字符串对象:

 public static String valueOf(byte n)

 public static String valueOf(int n)

 public static String valueOf(long n)

 public static String valueOf(float n)

 public static String valueOf(double n)

 例如:将形如123,12345.8等数值转换为字符串

 String str  =  String.valueOf(123)

 String str  =  String.valueOf(12345.8)

②可以使用toString方法(一个对象通过调用该方法可以获取该对象的字符串表示)

使用java.lang包中的Byte、Integer、Short、Long、Float、Double类调用相应的类方法,Integer.toString、Double.toString,

等等

例子:

Date date = new Date();
System.out.println(date.toString());

3.字符串与字符数组

①将字符数组转换为字符串对象

使用String类的构造方法:String(char a[])和String(char a[],int offset,int length)

分别用数组a中的全部字符和部分字符构造字符串对象

例子:

char a[] = {'1','2','3'};

System.out.println(new String(a).length());

②String类也提供了将字符串存放到数组中的办法: public void getChars(int start,int end,char c[],int offset);

例子:

char a[];

String s = "1945年8月15日是抗战胜利日";

s.getChars(11,15,a,0);

还有一个更加简练的方法将字符串中的全部字符存放到一个字符数组的办法:public char [] toCharArray();

例子:

int num = 10;

char s[] = new char[10];
s = Integer.toString(num).toCharArray();

猜你喜欢

转载自blog.csdn.net/qq_39445165/article/details/81672904
今日推荐