Java 中 关于字符串类型的转换

来源:互联网 发布:vv51软件下载 编辑:程序博客网 时间:2024/06/05 19:38

1、其它数据类型的转换成字符串型

通过查阅类库中各个类提供的成员方法可以看到,几乎java.lang.Object类派生的所有类提供了toString()方法,即将该类转换为字符串。例如:

Characrer,Integer,Float,Double,Boolean,Short等类的toString()方法分别用于将字符型、整型、浮点型、双精度浮点型、短整型等类转换为字符串。代码如下所示:


int i1=10;float f1=3.14f;double d1=3.1415926;

Integer I1=new Integer(i1);//生成Integer

Float F1=new Float(f1); //生成Float

Double D1=new Double(d1); //生成Double



//分别调用包装类的toString() 方法转换为字符串

String si1=I1.toString();

String sf1=F1.toString();

Stringsd1=D1.toString();

Sysytem.out.println("si1"+si1);

Sysytem.out.println("sf1"+sf1);Sysytem.out.println("sd1"+sd1);



2、字符串型转换成其它数据类型 

 (1)、字符串转换成其它类型:

字符串转换成整数:

String MyNumber ="1234";

int MyInt = Integer.parseInt(MyNumber);

字符串转换成byte, short, int, float, double, long 等数据类型,可以分别参考Byte, Short,Integer, Float, Double, Long 类的parseXXX 方法。

(2)、其它类型转换成字符串

整数转换成字符串:

int MyInt = 1234;

String MyString = "" + MyInt;

其它数据类型可以利用同样的方法转换成字符串。

 

0 0
原创粉丝点击