String常用方法总结

package com.example.demo.time;

import java.util.Arrays;
import java.util.Locale;
import java.util.function.IntConsumer;

/**
 * @author ChenQ2
 * @date 2023/2/13 3:41
 */
public class Test {

    public static void main(String[] args) {

        String string = "Hello World ";
        String china = "Hello China";

        // 判断两个字符串是否相等
        boolean equals = string.equals(china);
        System.out.println(equals); // false

        // 检测两个字符串是否相等.不区分大小写
        String str = "Hello world";
        boolean equalsIgnoreCase = string.equalsIgnoreCase(str);
        System.out.println(equalsIgnoreCase); // true

        // 判断字符串是否为空字符串.如果字符串为null会报错
        boolean empty = string.isEmpty();
        System.out.println(empty); // false

        // 返回当前索引位置上的字符串
        char charAt = string.charAt(1);
        System.out.println(charAt); // e

        // 按照字典位置,如果 string 在 e 之前,返回一个负数, 之后返回正数,相等则返回0
        String d = "d";
        int compareTo = d.compareTo("e");
        System.out.println(compareTo); // -1

        // 判断字符串是否保函 H
        boolean contains = string.contains("H");
        System.out.println(contains); // true

        // 字符串检索,返回开始位置,加上 ll 的长度(length)可以达到数据的准确返回,以后用于报文解析,如果查不到返回 -1
        int indexOf = string.indexOf("ll");
        System.out.println(indexOf); // 2

        // 判断字符串结尾是否包含 d
        boolean endsWith = string.endsWith("d");
        System.out.println(endsWith); // true

        // 判断字符串开始是否包含 H
        boolean startsWith = string.startsWith("H");
        System.out.println(startsWith); // true

        // 检索 l 最后一次出现的位置,返回索引
        int lastIndexOf = string.lastIndexOf("l");
        System.out.println(lastIndexOf); // 9

        // 包含 l 则替换成 L,如果不包含则不做改动
        String replace = string.replace("l", "L");
        System.out.println(replace); // HeLLo WorLd

        // 按照本地国家规则,全部转为小写
        String toLowerCase = string.toLowerCase(Locale.ROOT);
        System.out.println(toLowerCase); // hello world

        // 按照本地国家规则,全部转为大写
        String toUpperCase = string.toUpperCase(Locale.ROOT);
        System.out.println(toUpperCase); // HELLO WORLD

        // 去除在头部或者尾部小于等于U+0020的字符,如空格
        String trim = string.trim();
        System.out.println(trim + "111"); // "Hello World " -> Hello World111

        // 字符串手动入常量池
        String intern = string.intern();
        System.out.println(intern);

        // 判断字符串是否全部由数字组成
        System.out.println(isAllNumber("11221"));

    }

    /**
     * <P>
     * 判断字符串是否全部由数字组成
     * </P>
     * 
     * @param str
     * @return
     */
    public static boolean isAllNumber(String str) {
        // 将字符串转换为字符数组去处理
        char[] data = str.toCharArray();
        // 遍历寻找反例
        for (char a : data) {
            if (a < '0' || a > '9') {
                return false;
            }
        }
        return true;
    }
}

posted @ 2023-03-06 16:08  unknown-n2  阅读(28)  评论(0编辑  收藏  举报