字符串的转换相关方法-字符串的分割方法

字符串的转换相关方法

转换功能的方法

  • public char[] toCharArray () :将此字符串转换为新的字符数组。
  • public byte[] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组。
  • public String replace (CharSequence target, CharSequence replacement) :将与target匹配的字符串使 用replacement字符串替换。

方法演示,代码如下:

复制代码
 1 public class String_Demo03 {
 2 public static void main(String[] args) {
 3 //创建字符串对象
 4 String s = "abcde";
 5 // char[] toCharArray():把字符串转换为字符数组
 6 char[] chs = s.toCharArray();
 7 for(int x = 0; x < chs.length; x++) {
 8 System.out.println(chs[x]);
 9 }
10 System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
11 // byte[] getBytes ():把字符串转换为字节数组
12 byte[] bytes = s.getBytes();
13 for(int x = 0; x < bytes.length; x++) {
14 System.out.println(bytes[x]);
15 }
16 System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
17 // 替换字母it为大写IT
18 String str = "itcast itheima";
19 String replace = str.replace("it", "IT");
20 System.out.println(replace); // ITcast ITheima
21 System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
22 }
23 }
复制代码

CharSequence 是一个接口,也是一种引用类型。作为参数类型,可以把String对象传递到方法中。

字符串的分割方法

  public String[] split(String regex) :将此字符串按照给定的regex(规则)拆分为字符串数组。

方法演示,代码如下:

1
2
3
4
5
6
7
8
9
10
public class String_Demo03 {
public static void main(String[] args) {
//创建字符串对象
String s = "aa|bb|cc";
String[] strArray = s.split("|"); // ["aa","bb","cc"]
for(int x = 0; x < strArray.length; x++) {
System.out.println(strArray[x]); // aa bb cc
}
}
}

  

posted @   ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ  阅读(62)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示