java中String与int/float/double/byte/数组

原文链接:小宁博客[添加链接描述](https://www.sunxiaoning.com/language/634.html)

int转换为String(int i=100)

第一种方法:s=i+""; //会产生两个String对象
第二种方法:s=String.valueOf(i); //直接使用String类的静态方法,只产生一个对象。

String转换为int(Sting s=“100”)

第一种方法:i=Integer.parseInt(s); //直接使用静态方法,不会产生多余的对象,但会抛出异常
第二种方法:i=Integer.valueOf(s).intValue();//Integer.valueOf(s) 相当于 new Integer(Integer.parseInt(s)),也会抛异常,但会多产生一个对象,

字符串转换为float

float f = Float.parseFloat(str);

字符串转double

String str = “123.002”;Double d ;d = Double.parseDouble(str);

String转换为byte[]

String string = “hello world”;
byte[] bytes = string.getBytes();

byte[]转换为String

String s = new String(bytes);

通过Base64将String与byte进行转换

import java.util.Base64;
public class test 
{
    public static void main(String[] args) 
    {
        byte[] bytes = "hello world".getBytes();
        String encoded = Base64.getEncoder().encodeToString(bytes);
        byte[] decoded = Base64.getDecoder().decode(encoded);
		for(byte a : decoded)
			System.out.println(a);
        System.out.println( new String(decoded) );
    }
}

String转换为数组

String str = “a,b,bb,dd”;

  1. String[] strArr = str.split(",");
  2. char[] charArr = str.toCharArray();
  3. byte[] byteArr = str.getBytes();

字符数组转换为字符串:

char[] c1 = {‘a’,‘b’,‘c’};String str = new String(c1);

原文链接:小宁博客[添加链接描述](https://www.sunxiaoning.com/language/634.html)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值