您现在的位置是:首页 > 文章详情

Java 字符串 之 字符,字节,字符串的转换

日期:2018-09-10点击:585

http://www.verejava.com/?id=16993019638884

/**
题目: String 类的相关操作
    1. 字符与字符串转换操作
    2. 字节与字符串转换操作
    3. 判断操作
    4. 替换操作
    5. 字符串的截取
    6. 字符串的拆分
    7. 字符串的查找
    8. 字符串其他操作
*/
public class TestString1 {
    public static void main(String[] args) {
        //1.字符与字符串的转换
        //    1. char[] toCharArray()   字符串 转换成 字符数组
        //    2. char charAt(int index) 获取索引位置的字符
        //    3. int length()              获得字符总个数的方法
        //    4. String new String(char[] value) 将字符数组转换成字符串
        //    5. String new String(char[] value,int offset,int count) 将字符数组从        offset索引开始的count个字符转换成字符串
        String str = "Hello Welcome";
        //说明: 将字符串转换成字符数组输出
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            System.out.println(chars[i]);
        }

        System.out.println("\n-------------------");
        //说明: 直接通过索引获取字符输出
        for (int i = 0; i < str.length(); i++) {
            System.out.println(str.charAt(i));
        }

        System.out.println("\n-------------------");
        //说明: 将字符数组转换成字符串
        char[] chars2 = { 'G', 'o', 'o', 'd', ' ', 'M', 'o', 'r', 'n', 'i', 'n', 'g' };
        System.out.println(new String(chars2));
        System.out.println(new String(chars2, 0, 4));

        System.out.println("\n----------------------");
        //2. 字节与字符串的转换
        //    1. byte[] getBytes() 将字符串转换成字节数组
        //    2. String new String(byte[] bytes) 将字节数组转换成字符串
        //    3. String new String(byte[] bytes,int offset,int count) 将字节数组从    
        //        offset 索引开始的 count 个字节转换成字符串

        //    作用: 因为java中数据是以字节byte为单位传输的,所以在以后输入输出流I/O当中用到
        //说明: 将字符串转换成字节数组打印输出
        String str3 = "How are you";
        byte[] bytes = str3.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i] + "-" + (char) bytes[i]);
        }

        //说明: 将字节数组转换成字符串输出
        byte[] bytes2 = { 65, 66, 67, 68 };
        System.out.println(new String(bytes2));
        System.out.println(new String(bytes2, 0, 2));

    }
}

http://www.verejava.com/?id=16993019638884

原文链接:https://yq.aliyun.com/articles/637957
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章