Java筛选出String中带后缀字符

引言

在日常开发中,我们经常需要从字符串中筛选出带有特定后缀的字符串。例如,从文件列表中筛选出所有以 ".txt" 结尾的文件名,或者从邮箱列表中筛选出所有以 "@gmail.com" 结尾的邮箱地址等。本文将使用Java语言来讲解如何实现这样的筛选功能。

问题描述

假设我们有一个String数组,其中包含多个字符串。我们需要筛选出所有以指定后缀结尾的字符串,并将它们保存到一个新的列表中。

解决方案

我们可以使用Java提供的String类的endsWith()方法来判断一个字符串是否以指定后缀结尾。然后,我们可以通过循环遍历字符串数组,对每个字符串进行判断,并将符合条件的字符串添加到一个新的列表中。

下面是一个使用Java实现的示例代码:

import java.util.ArrayList;
import java.util.List;

public class StringSuffixFilter {
    public static List<String> filterStringsBySuffix(String[] strings, String suffix) {
        List<String> filteredStrings = new ArrayList<>();
        for (String str : strings) {
            if (str.endsWith(suffix)) {
                filteredStrings.add(str);
            }
        }
        return filteredStrings;
    }

    public static void main(String[] args) {
        String[] strings = {"file1.txt", "file2.txt", "file3.jpg", "file4.txt"};
        String suffix = ".txt";
        List<String> filteredStrings = filterStringsBySuffix(strings, suffix);
        System.out.println("Filtered strings:");
        for (String str : filteredStrings) {
            System.out.println(str);
        }
    }
}

在上述代码中,我们定义了一个名为filterStringsBySuffix()的静态方法,该方法接受一个字符串数组和一个后缀作为参数,并返回一个符合条件的字符串列表。在方法中,我们循环遍历字符串数组,对每个字符串使用endsWith()方法进行判断,如果以指定后缀结尾,则将其添加到新的列表中。最后,我们在main()方法中使用示例字符串数组和后缀来测试该方法,并打印筛选结果。

流程图

下面是使用mermaid语法表示的流程图:

flowchart TD
    A[开始] --> B[初始化filteredStrings列表]
    B --> C[循环遍历字符串数组]
    C --> D{字符串以指定后缀结尾?}
    D -- 是 --> E[将字符串添加到filteredStrings列表]
    D -- 否 --> C
    C --> F[循环结束]
    F --> G[输出filteredStrings列表]
    G --> H[结束]

状态图

下面是使用mermaid语法表示的状态图:

stateDiagram
    [*] --> 初始化filteredStrings列表
    初始化filteredStrings列表 --> 循环遍历字符串数组
    循环遍历字符串数组 --> 字符串以指定后缀结尾?
    字符串以指定后缀结尾? --> 添加字符串到filteredStrings列表
    字符串以指定后缀结尾? --> 循环遍历字符串数组
    添加字符串到filteredStrings列表 --> 循环遍历字符串数组
    循环遍历字符串数组 --> 输出filteredStrings列表
    输出filteredStrings列表 --> [*]

总结

本文介绍了如何使用Java语言筛选出字符串数组中带有指定后缀的字符串。我们通过使用String类的endsWith()方法,并结合循环和条件判断,实现了一个简单但实用的筛选功能。希望本文能够帮助读者理解和掌握这一常见的字符串处理技巧。