String 72变 ---------各种字符串处理方法

Java 的常用字符串处理方法的详细介绍     总会用到的

字符串的基本处理

1. 字符串创建和初始化

  • 使用字符串字面量

    1String str = "Hello, World!";
  • 使用 new 关键字

    1String str = new String("Hello, World!");

2. 获取字符串长度

  • 使用 length() 方法
    1String str = "Hello";
    2int length = str.length(); // length == 5

3. 字符串拼接

  • 使用 + 运算符

    1String s1 = "Hello";
    2String s2 = "World";
    3String result = s1 + " " + s2; // result == "Hello World"
  • 使用 StringBuilderStringBuffer

    1StringBuilder sb = new StringBuilder();
    2sb.append("Hello").append(" ").append("World");
    3String result = sb.toString(); // result == "Hello World"

    对于多线程环境,推荐使用 StringBuffer

    1StringBuffer sb = new StringBuffer();
    2sb.append("Hello").append(" ").append("World");
    3String result = sb.toString(); // result == "Hello World"

4. 字符串分割

  • 使用 split() 方法
    1String str = "apple,banana,orange";
    2String[] parts = str.split(",");
    3// parts == ["apple", "banana", "orange"]
5. 字符串替换
  • 使用 replace() 方法

    1String str = "Hello, World!";
    2String replaced = str.replace("World", "Java");
    3// replaced == "Hello, Java!"
  • 使用 replaceAll() 方法

    1String str = "Hello, World! Hello, World!";
    2String replaced = str.replaceAll("World", "Java");
    3// replaced == "Hello, Java! Hello, Java!"
  • 使用 replaceFirst() 方法

    1String str = "Hello, World! Hello, World!";
    2String replaced = str.replaceFirst("World", "Java");
    3// replaced == "Hello, Java! Hello, World!"

6. 字符串截取

  • 使用 substring() 方法
    1String str = "Hello, World!";
    2String subStr = str.substring(7, 12); // subStr == "World"

7. 字符串比较

  • 使用 equals() 方法

    1String str1 = "Hello";
    2String str2 = "Hello";
    3boolean isEqual = str1.equals(str2); // isEqual == true
  • 使用 equalsIgnoreCase() 方法

    1String str1 = "Hello";
    2String str2 = "hello";
    3boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // isEqualIgnoreCase == true

8. 字符串查找

  • 使用 indexOf() 方法

    1String str = "Hello, World!";
    2int index = str.indexOf("World"); // index == 7
  • 使用 lastIndexOf() 方法

    1String str = "Hello, World! Hello, again!";
    2int lastIndex = str.lastIndexOf("Hello"); // lastIndex == 14
  • 使用 contains() 方法

    1String str = "Hello, World!";
    2boolean contains = str.contains("World"); // contains == true

9. 字符串转换

  • 转换为大写或小写

    1String str = "Hello, World!";
    2String upperCase = str.toUpperCase(); // upperCase == "HELLO, WORLD!"
    3String lowerCase = str.toLowerCase(); // lowerCase == "hello, world!"
  • 去除空白字符

    1String str = "  Hello, World!  ";
    2String trimmed = str.trim(); // trimmed == "Hello, World!"

10. 字符串格式化

  • 使用 String.format() 方法

    1String formatted = String.format("Hello, %s!", "World");
    2// formatted == "Hello, World!"
  • 使用 MessageFormat

    1String template = "Hello, {0}!";
    2String formatted = MessageFormat.format(template, "World");
    3// formatted == "Hello, World!"

11. 字符串转数组

  • 将字符串转换为字符数组

    1String str = "Hello";
    2char[] chars = str.toCharArray(); // chars == ['H', 'e', 'l', 'l', 'o']
  • 将字符串转换为字符串数组

    1String str = "apple,banana,orange";
    2String[] parts = str.split(",");
    3// parts == ["apple", "banana", "orange"]

12. 字符串与基本类型的转换

  • 字符串转整数

    1String str = "123";
    2int number = Integer.parseInt(str); // number == 123
  • 字符串转浮点数

    1String str = "123.45";
    2double number = Double.parseDouble(str); // number == 123.45
  • 字符串转布尔值

    1String str = "true";
    2boolean bool = Boolean.parseBoolean(str); // bool == true

14. 字符串的正则表达式处理

  • 使用 matches() 方法

    1String str = "123-456-7890";
    2boolean matches = str.matches("\\d{3}-\\d{3}-\\d{4}"); // matches == true
  • 使用 replaceAll() 方法

    1String str = "Hello, World! 123";
    2String replaced = str.replaceAll("\\d+", ""); // replaced == "Hello, World! "

15. 字符串的空值处理

  • 检查字符串是否为空或空字符串
    1String str = "";
    2boolean isEmpty = str.isEmpty(); // isEmpty == true
    3
    4String str2 = null;
    5boolean isNullOrEmpty = (str2 == null || str2.isEmpty()); // isNullOrEmpty == true


处理字符串常用的第三方库

                

                在 Java 中,除了标准库提供的字符串处理功能之外,还有一些第三方库提供了更为强大和方便的字符串处理工具。这些库通常提供了更多的功能,更高的性能,以及更好的易用性。下面是一些常用的第三方工具类库及其简介。

1. Apache Commons Lang

Apache Commons Lang 是一个流行的 Java 实用工具包,它提供了很多扩展 Java 标准库的功能,其中包括一些强大的字符串处理工具类。

  • StringUtils:提供了许多有用的静态方法来处理字符串,如 isEmpty(), isBlank(), join(), split(), leftPad(), rightPad(), center(), reverse(), capitalize(), uncapitalize(), abbreviate(), abbreviateMiddle(), strip(), stripStart(), stripEnd() 等。

     

    示例

    1import org.apache.commons.lang3.StringUtils;
    2
    3String str = "  Hello, World!  ";
    4String trimmed = StringUtils.strip(str); // trimmed == "Hello, World!"
    5
    6String joined = StringUtils.join(new String[]{"Hello", "World"}, ", ");
    7// joined == "Hello, World"
    8
    9String reversed = StringUtils.reverse("Hello");
    10// reversed == "olleH"
  • StringEscapeUtils:提供了用于转义和取消转义字符串的方法,如 escapeHtml4(), unescapeHtml4(), escapeJava(), unescapeJava() 等。

     

    示例

    1import org.apache.commons.lang3.StringEscapeUtils;
    2
    3String escaped = StringEscapeUtils.escapeHtml4("<script>alert('XSS');</script>");
    4// escaped == "&lt;script&gt;alert(&#x27;XSS&#x27;);&lt;/script&gt;"
    5
    6String unescaped = StringEscapeUtils.unescapeHtml4(escaped);
    7// unescaped == "<script>alert('XSS');</script>"

2. Apache Commons Text

Apache Commons Text 是 Apache Commons Lang 3.x 分离出来的一个项目,专注于文本处理相关的功能。

  • StringSubstitutor:用于模板字符串替换。

     

    示例

    1import org.apache.commons.text.StringSubstitutor;
    2
    3String template = "Hello, ${name}!";
    4StringSubstitutor substitutor = new StringSubstitutor(Map.of("name", "World"));
    5String result = substitutor.replace(template);
    6// result == "Hello, World!"
  • WordUtils:提供了用于处理单词的方法,如 capitalizeFully(), uncapitalize(), wrap() 等。

     

    示例

    1import org.apache.commons.text.WordUtils;
    2
    3String capitalized = WordUtils.capitalizeFully("hello world");
    4// capitalized == "Hello World"
    5
    6String wrapped = WordUtils.wrap("This is a very long string that will be wrapped after every twenty characters.", 20);
    7// wrapped == "This is a very long\nstring that will be\nwrapped after every\ntwenty characters."

3. Guava

Guava 是 Google 提供的一个开源 Java 库,它提供了丰富的集合类、缓存机制、原生类型的封装类等,同时也包括了一些字符串处理工具。

  • Strings:提供了 nullToEmpty(), commonPrefix(), commonSuffix(), join(), split(), padStart(), padEnd(), repeat(), collapseWhitespace() 等方法。

     

    示例

    1import com.google.common.base.Strings;
    2
    3String str = null;
    4String safeStr = Strings.nullToEmpty(str); // safeStr == ""
    5
    6String repeated = Strings.repeat("*-", 5); // repeated == "*-*-*-*-*-"

4. Apache Calcite

虽然 Apache Calcite 主要用于 SQL 解析和优化,但它也提供了一个 org.apache.calcite.sql.parser.SqlParser 类,可以用来解析 SQL 语句,对于复杂的字符串处理(如 SQL 注入防御)可能有用。

5. Java 8 及以上版本的新特性

  • String.join():自 Java 8 起,String 类提供了 join() 方法,可以直接用于连接字符串数组或集合。

     

    示例

    1String joined = String.join(", ", Arrays.asList("Hello", "World"));
    2// joined == "Hello, World"
  • String.formatted():自 Java 15 起,String 类提供了 formatted() 方法,类似于 String.format(),但更简洁。

     

    示例

    1String formatted = String.formatted("Hello, %s!", "World");
    2// formatted == "Hello, World!"

6. StringTemplate

StringTemplate 是一个由 Terence Parr 开发的模板引擎,它允许你在 Java 中定义模板并填充数据来生成字符串。

总结

以上列出的库和工具类可以极大地简化字符串处理的工作,提高开发效率。选择合适的工具类库取决于你的具体需求和项目的依赖情况。如果你的应用需要高性能的字符串处理功能,或者你希望减少代码量并提高可读性和维护性,可以考虑引入这些第三方库。


常用工具类StringUtils详细介绍

单独拿出来说,是因为在目前项目中用的最多的字符处理工具类就是这个。

基本信息

  • : Apache Commons Lang
  • 包路径org.apache.commons.lang3.StringUtils
  • 适用场景: 字符串处理、校验、格式化等

常用方法

1. 字符串校验
  • isEmpty(String str):

  • 判断字符串是否为空 (null) 或空白字符串 ("")。

    1boolean empty = StringUtils.isEmpty(null); // true
    2boolean empty2 = StringUtils.isEmpty(""); // true
    3boolean notEmpty = StringUtils.isEmpty("text"); // false
  • isBlank(String str):

  • 判断字符串是否为空 (null) 或只包含空白字符(如空格、制表符等)。

    1boolean blank = StringUtils.isBlank(" "); // true
    2boolean notBlank = StringUtils.isBlank("text"); // false
  • isNotEmpty(String str):

  • 反之,判断字符串是否非空或非空白。

    1boolean notEmpty = StringUtils.isNotEmpty("text"); // true
    2boolean empty = StringUtils.isNotEmpty(""); // false
  • isNotBlank(String str):

  • 反之,判断字符串是否非空且不全为空白字符。

    1boolean notBlank = StringUtils.isNotBlank(" text "); // true
    2boolean blank = StringUtils.isNotBlank(" "); // false
2. 字符串拼接
  • join(Iterable<?> elements, String separator):

  • 将迭代器中的元素以指定的分隔符拼接成一个字符串。

    1String joined = StringUtils.join(new String[]{"Hello", "World"}, ", ");
    2// joined == "Hello, World"
  • join(Object... elements, String separator):

  • 将数组中的元素以指定的分隔符拼接成一个字符串。

    1String joined = StringUtils.join(new Object[]{"Hello", "World"}, ", ");
    2// joined == "Hello, World"
3. 字符串分割
  • split(String str, int max):

  • 按照指定的最大数量分割字符串。

    1String[] parts = StringUtils.split("apple,banana,orange", ',');
    2// parts == ["apple", "banana", "orange"]
  • splitPreserveAllTokens(String str, char separatorChar):

  • 按照指定的分隔符分割字符串,即使分隔符出现在末尾也会保留。

    1String[] parts = StringUtils.splitPreserveAllTokens("apple,banana,,orange", ',');
    2// parts == ["apple", "banana", "", "orange"]
4. 字符串填充
  • leftPad(String str, int size, char padChar):

  • 将字符串左侧填充至指定长度。

    1String padded = StringUtils.leftPad("123", 5, '0');
    2// padded == "00123"
  • rightPad(String str, int size, char padChar):

  • 将字符串右侧填充至指定长度。

    1String padded = StringUtils.rightPad("123", 5, '0');
    2// padded == "12300"
  • center(String str, int size, char padChar):

  • 将字符串居中填充至指定长度。

    1String centered = StringUtils.center("123", 5, '0');
    2// centered == "01230"
5. 字符串替换
  • replace(String text, String searchString, String replacement):

  • 替换字符串中的子串。

    1String replaced = StringUtils.replace("Hello, World!", "World", "Java");
    2// replaced == "Hello, Java!"
  • replaceAll(String text, String regex, String replacement):

  • 使用正则表达式替换字符串中的子串。

    1String replaced = StringUtils.replaceAll("Hello, World! 123", "\\d+", "");
    2// replaced == "Hello, World! "
  • replaceEach(String text, String[] searchList, String[] replacementList): 使用多个搜索字符串和替换字符串进行替换。

    1String replaced = StringUtils.replaceEach("The quick brown fox", new String[]{"quick", "brown"}, new String[]{"slow", "red"});
    2// replaced == "The slow red fox"

6. 字符串转换
  • capitalize(String str):

  • 将字符串首字母大写。

    1String capitalized = StringUtils.capitalize("hello");
    2// capitalized == "Hello"
  • uncapitalize(String str):

  • 将字符串首字母小写。

    1String uncapitalized = StringUtils.uncapitalize("Hello");
    2// uncapitalized == "hello"
  • swapCase(String str):

  • 交换字符串中每个字符的大小写。

    1String swapped = StringUtils.swapCase("HeLlO wOrLd");
    2// swapped == "hElLo WoRlD"
  • reverse(String str):

  • 反转字符串。

    1String reversed = StringUtils.reverse("hello");
    2// reversed == "olleh"
7. 字符串缩略
  • abbreviate(String str, int maxLen):

  • 将字符串缩短到指定长度,并在末尾添加省略号。

    1String abbreviated = StringUtils.abbreviate("Hello, World!", 10);
    2// abbreviated == "Hello, Wor..."
  • abbreviateMiddle(String str, int middleOffset, int length):

  • 在中间部分缩略字符串。

    1String abbreviated = StringUtils.abbreviateMiddle("Hello, World!", 5, 3);
    2// abbreviated == "Hello, W..."

示例代码

1import org.apache.commons.lang3.StringUtils;
2
3public class StringUtilsExample {
4    public static void main(String[] args) {
5        String text = "  Hello, World!  ";
6
7        // 校验字符串是否为空或空白
8        boolean isEmpty = StringUtils.isEmpty(text); // false
9        boolean isBlank = StringUtils.isBlank(text); // false
10
11        // 去除空白
12        String trimmed = StringUtils.strip(text); // "Hello, World!"
13
14        // 字符串拼接
15        String joined = StringUtils.join(new String[]{"Hello", "World"}, ", ");
16        // joined == "Hello, World"
17
18        // 字符串替换
19        String replaced = StringUtils.replace(text, "World", "Java");
20        // replaced == "  Hello, Java!  "
21
22        // 字符串填充
23        String padded = StringUtils.leftPad("123", 5, '0');
24        // padded == "00123"
25
26        // 字符串转换
27        String capitalized = StringUtils.capitalize("hello");
28        // capitalized == "Hello"
29
30        // 字符串缩略
31        String abbreviated = StringUtils.abbreviate("Hello, World!", 10);
32        // abbreviated == "Hello, Wor..."
33
34        System.out.println("Trimmed: " + trimmed);
35        System.out.println("Joined: " + joined);
36        System.out.println("Replaced: " + replaced);
37        System.out.println("Padded: " + padded);
38        System.out.println("Capitalized: " + capitalized);
39        System.out.println("Abbreviated: " + abbreviated);
40    }
41}


字符处理  实际开发的应用场景

字符处理在实际开发中的应用场景非常广泛,几乎涵盖了所有类型的软件开发。下面列举了一些具体的场景。

1. Web 开发

  • 表单验证:在用户提交表单时,需要验证输入的合法性,如邮箱地址、电话号码等。这通常涉及到字符串的正则表达式匹配。

    1import java.util.regex.Pattern;
    2
    3public class FormValidation {
    4    public static boolean isValidEmail(String email) {
    5        String regex = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$";
    6        Pattern pattern = Pattern.compile(regex);
    7        return pattern.matcher(email).matches();
    8    }
    9}
  • URL 处理:在处理 URL 时,需要对 URL 进行解析、编码或解码。

    1import java.net.URLEncoder;
    2import java.net.URLDecoder;
    3import java.nio.charset.StandardCharsets;
    4
    5public class URLHandling {
    6    public static String encodeURL(String url) {
    7        return URLEncoder.encode(url, StandardCharsets.UTF_8);
    8    }
    9
    10    public static String decodeURL(String encodedUrl) {
    11        return URLDecoder.decode(encodedUrl, StandardCharsets.UTF_8);
    12    }
    13}
  • HTML/CSS 格式化:在生成或解析 HTML/CSS 时,需要处理标签、属性等。

    1public class HTMLFormatting {
    2    public static String formatHTML(String html) {
    3        // 假设使用一个库来格式化 HTML
    4        return HtmlFormatter.format(html);
    5    }
    6}

2. 数据库操作

  • SQL 查询构建:动态生成 SQL 查询语句,需要处理变量插入和转义。

    1public class SQLQueryBuilder {
    2    public static String buildSelectQuery(String table, String[] columns, String whereClause) {
    3        StringBuilder query = new StringBuilder("SELECT ");
    4        if (columns != null && columns.length > 0) {
    5            query.append(String.join(", ", columns));
    6        } else {
    7            query.append("*");
    8        }
    9        query.append(" FROM ").append(table);
    10        if (whereClause != null && !whereClause.isEmpty()) {
    11            query.append(" WHERE ").append(whereClause);
    12        }
    13        return query.toString();
    14    }
    15}
  • SQL 注入防御:使用预编译语句或参数化查询来避免 SQL 注入。

    1public class SQLInjectionPrevention {
    2    public static void executeQuery(String query, Object... params) {
    3        try (PreparedStatement pstmt = connection.prepareStatement(query)) {
    4            for (int i = 0; i < params.length; i++) {
    5                pstmt.setObject(i + 1, params[i]);
    6            }
    7            ResultSet rs = pstmt.executeQuery();
    8            // 处理结果集...
    9        } catch (SQLException e) {
    10            e.printStackTrace();
    11        }
    12    }
    13}

3. 数据分析

  • 文本清洗:在处理文本数据时,需要去除噪声、标点符号、停用词等。

    1import java.util.Arrays;
    2import java.util.List;
    3import org.apache.commons.lang3.StringUtils;
    4
    5public class TextCleaning {
    6    public static List<String> cleanText(String text) {
    7        String cleanedText = StringUtils.stripAccents(text).toLowerCase();
    8        cleanedText = cleanedText.replaceAll("[^a-zA-Z0-9 ]", "").trim();
    9        return Arrays.asList(cleanedText.split("\\s+"));
    10    }
    11}
  • 数据标准化:将不同来源的数据统一格式。

    1public class DataStandardization {
    2    public static String standardizeDate(String date) {
    3        // 假设 date 的格式为 "MM/dd/yyyy"
    4        String[] parts = date.split("/");
    5        return String.format("%s-%s-%s", parts[2], parts[0], parts[1]);
    6    }
    7}

总结

                字符处理在实际开发中的应用场景非常广泛,涵盖了从简单的字符串操作到复杂的文本分析等多个层面。掌握好字符处理技巧对于提高软件的质量、增强系统的功能性和安全性都有着重要的意义。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值