字符,字节与字符串的一些常见操作

  
  

一.字符与字符串


  字符串内部包含一个字符数组,String可以和char[]相互转换

1.将字符数组中的所有内容变为字符串

public String(char value[])

2.将部分字符数组中的内容变为字符串

public String(char value[],int offset,int count)  //offset代表偏移量,count代表个数


参考代码:

public class Test {
    public static void main(String[] args) {
        char[] arr={'a','b','c','d'};
        //将整体字符数组变为字符串
        String arr1=new String(arr);
        System.out.println(arr1);
        //将部分字符数组内容变为字符串
        String arr2=new String(arr,1,2);
        System.out.println(arr2);
    }
}

//打印结果
abcd
bc

上述两种属于构造类型


3.取得指定索引位置的字符,索引从0开始

public char charAt(int index)

参考代码:

public class Test{
    public static void main(String[] args) {
        String arr="abcde";
        char a=arr.charAt(2);
        System.out.println(a);
    }
}

//打印结果
c



4.将字符串变为字符数组返回

public  char[]  toCharArray()

参考代码:

public class Test{
    public static void main(String[] args) {
       String arr="abcde";
        char[] arr1=arr.toCharArray();
        for (char x:arr1) {
            System.out.print(x+" ");
        }
    }
}

//打印结果
a b c d e 

上述两种属于普通类型




二.字节与字符串

  字节常用于数据传输以及编码转换的处理之中

1.将字节数组变为字符串

public String(byte bytes[])

2.将部分字节数组中的内容变为字符串

public String(byte bytes[],int offset,int length)

3.将字符串以字节数组的形式返回

public byte[] getBytes()

4.编码转换处理

public byte[] getBytes(String charsetName)throws UnsupportedEncodingException



参考代码:

public class Test{

    public static void main(String[] args) {
        String str="helloword";
        //String转byte[]数组
        byte[] data=str.getBytes();
        for(int i=0;i<data.length;i++){
            System.out.print(data[i]+" ");
        }
        System.out.println();

        //byte[] 转String
        System.out.println(new String(data));
    }
}

//打印结果
104 101 108 108 111 119 111 114 100 
helloword



小结:

何时使用byte[] 何时使用char[] ?

1.byte[]是把String按照一个字节一个字节的方式处理,这种适合在网络传输,数据存储这样的情境下使用
2.char[]是把String按照一个字符一个字符的方式处理,更适合文本数据的操作

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值