字符串截取方法测试。

从指定的字符串中截取特定范围内的字符串或字符:

 

 

package com.example.string;

/**
 * 从字符串中截取指定范围的子字符串或字符。Extract the string.
 * substring 的起始索引是 0,从索引 0 开始就是从第一个字符开始往后查找并截取到截止索引处。
 * 从索引 1 开始就是舍弃第 1 个字符,从第 2 个字符来说查找并截取到截止索引处。
 * 截止索引默认为原字符串的长度。
 * 起始索引包含,截止索引不包含。所以要取前 10 个字符就需要将截止索引设置为 10,而非 9,起始索引自然是 0.
 * 基础知识:索引(index)是从零开始的。
 */
public class SubstringTest {

    public static void main(String[] args) {
        String source = "2025-11-07 10:50:36 598";
        int length = source.length();
        int firstIndex = source.indexOf("2");
        int lastIndex = source.lastIndexOf("8");
        int dayIndex = source.indexOf("7");

        System.out.println("原日期:" + source + ",长度 = " + length + ",首字符的索引 = "
                + source.indexOf("2") + ",尾字符的索引 = " + source.lastIndexOf("8"));
        System.out.println("日的索引 = " + dayIndex);
//        System.out.println("首字符的索引 = " + firstIndex);
//        System.out.println("尾字符的索引 = " + lastIndex);

        String target = source.substring(0);    // 截止日期默认为最后一个。
        System.out.println("从 0 开始截取直至末尾后的日期:" + target);

        target = source.substring(firstIndex, lastIndex);
        System.out.println("从首索引开始截取直至尾索引为止后的日期:" + target);

        target = source.substring(firstIndex, length);
        System.out.println("从首索引开始截取直至其长度位置为止后的日期:" + target);

        target = source.substring(0, 1);   
        System.out.println("从 0 开始截取 1 个字符后的日期:" + target);

        target = source.substring(0, 9);   
        System.out.println("从 0 开始截取 9 个字符后的日期:" + target);

        target = source.substring(1, 10);   
        System.out.println("从 0 开始截取 9 个字符后的日期:" + target);

        target = source.substring(0, 10);
        System.out.println("从 0 开始截取 10 个字符后的日期:" + target);

//        target = source.substring(25, 30);
        /*
         * 起始索引和截止索引都不可超过尾字符的索引,否则抛出如下错误。
         * Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 25, end 30, length 23
         *     at java.base/java.lang.String.checkBoundsBeginEnd(String.java:4602)
         *     at java.base/java.lang.String.substring(String.java:2705)
         */
    }

}

 

posted @ 2025-11-05 11:52  hapday  阅读(7)  评论(0)    收藏  举报