|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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通