字符串转数组

简介: 字符串转数组

字符串转数组
public static void main(String[] args) {

    String str = new String("abcd");
    char[] ch = str.toCharArray();
    for (int i = 0; i < ch.length; i++) {
        System.out.print(ch[i]+" ");
    }
}

1
2
3
4
5
6
7

  1. 格式化字符串

public static void main(String[] args) {

    String str = String.format("%d-%d-%d",2022,8,31);
    System.out.println(str);
}

1
2
3
4

五、字符串截取与替换

  1. trim()

去掉字符串左右所有的空格会去掉字符串开头和结尾的空白字符(空格, 换行, 制表符等

public static void main(String[] args) {

    String str = "  hello    ";
    System.out.println(str.trim());
}

1
2
3
4

  1. subString()

传入一个参数,是截取此位置到结尾.

public static void main(String[] args) {

    String str = "hello world!";
    System.out.println(str.substring(6));
}

1
2
3
4

传入两个参数,是截取指定范围内容

public static void main(String[] args) {

    String str = "woyaojindachang";
    System.out.println(str.substring(2,8));
}

1
2
3
4

3.replace()
使用一个指定的新的字符串替换掉已有的字符串数据,可用的方法如下:

public static void main(String[] args) {

    String str = new String("2022.8.31");
    System.out.println(str.replace('.','-'));
}

1
2
3
4

如果只想替换第一个内容使用replaceFirst()即可

六、字符串拆分
方法 功能
String[] split(String regex) 字符串全部拆分
String[] split(String regex, int limit) 将字符串以指定的格式,拆分为limit组
public static void main(String[] args) {

    String str = "wo yao jin da chang";
    String[] arr = str.split(" ");
    for (String s: arr) {
        System.out.println(s);
    }
}

1
2
3
4
5
6
7

public static void main(String[] args) {

    String str = "wo yao jin da chang";
    String[] arr = str.split(" ",2);
    for (String s: arr) {
        System.out.println(s);
    }
}

1
2
3
4
5
6
7

特殊情况的拆分:
1.如果一个字符串中有多个分隔符,可以用"|"作为连字符.

public static void main(String[] args) {

    String str = "wo&jin=da=chang";
    String[] arr = str.split("=|&");
    for (String s:arr) {
        System.out.println(s);
    }
}

1
2
3
4
5
6
7

  1. 字符"|“,”*“,”+"都得加上转义字符,前面加上 “\”

public static void main(String[] args) {

    String str = "2002.8.31";
    String[] s = str.split("\\.");
    for (String ss:s) {
        System.out.println(ss);
    }
}

1
2
3
4
5
6
7

  1. 如果是 “” ,那么就得写成 “\” .

public static void main(String[] args) {

    String str = "2002\\8\\31";
    String[] s = str.split("\\\\");
    for (String ss:s) {
        System.out.println(ss);
    }
}
相关文章
|
4月前
|
Java
数组的练习
数组的练习
|
2天前
|
存储 算法 编译器
C 数组详解
在C语言中,数组是一种用于存储多个同类型数据的集合。本文介绍了数组的基本特性与使用方法,包括定义与初始化、索引访问、多维数组、指针操作、大小计算及函数传递等内容。数组名可视为指向首元素的指针,支持遍历、排序与查找等常见操作。数组大小固定,访问越界会导致未定义行为。此外,还可以将数组嵌套在结构体中以增加数据复杂性。
20 10
|
3月前
|
存储 开发框架 .NET
C#中的数组探索
C#中的数组探索
|
11月前
|
存储 C语言
C 数组
C 数组。
29 0
|
4月前
|
存储 C++ 索引
C++数组
C++数组
|
4月前
1-9 数组
1-9 数组
20 0
|
4月前
|
存储 人工智能 算法
4.为何数组下表从0开始
4.为何数组下表从0开始
57 1
|
4月前
|
存储 C语言
数组
数组。
23 0
|
4月前
|
存储 程序员 C++
数组相关练习
数组相关练习
48 0