|NO.Z.00019|——————————|BigDataEnd|——|Java&核心类库.V04|——|Java.v04|string类.v04|数组之间转换|

一、string类型和数组之间的转换:常用的成员方法(练熟、记住)
方法声明 功能介绍
String toString() 返回字符串本身
byte[] getBytes() 将当前字符串内容转换为byte数组并返回
char[] toCharArray() 用于将当前字符串内容转换为char数组并返回
二、编程代码
package com.yanqi.task12;

public class StringByteCharTest {

    public static void main(String[] args) {

        // 1.创建String类型的对象并打印
        String str1 = new String("world");
        System.out.println("str1 = " + str1); // world

        System.out.println("-----------------------------------------------");
        // 2.实现将String类型转换为byte数组类型并打印
        // 思路:先将字符串拆分为字符,将再每个字符转换为byte类型,也就是获取所有字符的ASCII
        byte[] bArr = str1.getBytes();
        for (int i = 0; i < bArr.length; i++) {
            System.out.println("下标为i的元素是:" + bArr[i]);
        }
        // 将byte数组转回String类型并打印
        String str2 = new String(bArr);
        System.out.println("转回字符串为:" + str2); // world

        System.out.println("-----------------------------------------------");
        // 3.实现将String类型转换为char数组类型并打印
        // 思路:将字符串拆分为字符并保存到数组中
        char[] cArr = str1.toCharArray();
        for (int i = 0; i < cArr.length; i++) {
            System.out.println("下标为" + i + "的字符是:" + cArr[i]);
        }
        // 将char数组转回String类型并打印
        String str3 = new String(cArr);
        System.out.println("转回字符串为:" + str3); // world
    }
}
三、编译打印
D:\JAVA\jdk-11.0.2\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=51800:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath E:\NO.Z.10000——javaproject\NO.H.00001.javase\javase\out\production\javase com.yanqi.task12.StringByteCharTest
str1 = world
-----------------------------------------------
下标为i的元素是:119
下标为i的元素是:111
下标为i的元素是:114
下标为i的元素是:108
下标为i的元素是:100
转回字符串为:world
-----------------------------------------------
下标为0的字符是:w
下标为1的字符是:o
下标为2的字符是:r
下标为3的字符是:l
下标为4的字符是:d
转回字符串为:world

Process finished with exit code 0

 
 
 
 
 
 
 
 
 

Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
                                                                                                                                                   ——W.S.Landor

 

posted on   yanqi_vip  阅读(2)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示