返回

String 类型常用 API

前端

查询

String 类型提供了多种查询方法,用于确定字符串中是否包含指定的子字符串。常用的查询方法包括:

  • startsWith() :检查字符串是否以指定的子字符串开头。
  • endsWith() :检查字符串是否以指定的子字符串结尾。
  • includes() :检查字符串是否包含指定的子字符串。

以下示例演示了如何使用 startsWith()、endsWith() 和 includes() 方法:

String str = "Hello, world!";

System.out.println(str.startsWith("Hello")); // true
System.out.println(str.endsWith("!")); // true
System.out.println(str.includes("world")); // true

拼接/截取

String 类型提供了多种方法用于拼接或截取字符串。常用的拼接/截取方法包括:

  • concat() :将两个字符串连接起来。
  • substring() :截取字符串的一部分。
  • replace() :将字符串中的一部分替换为另一个字符串。

以下示例演示了如何使用 concat()、substring() 和 replace() 方法:

String str1 = "Hello";
String str2 = "world!";

System.out.println(str1.concat(str2)); // Hello, world!
System.out.println(str1.substring(1, 4)); // ell
System.out.println(str1.replace("Hello", "Hi")); // Hi, world!

去空格

String 类型提供了 trim() 方法用于去除字符串首尾的空格。

以下示例演示了如何使用 trim() 方法:

String str = " Hello, world! ";

System.out.println(str.trim()); // Hello, world!

填充字符

String 类型提供了 padStart() 和 padEnd() 方法用于在字符串首尾填充指定的字符。

以下示例演示了如何使用 padStart() 和 padEnd() 方法:

String str = "Hello";

System.out.println(str.padStart(10, '0')); // 00000Hello
System.out.println(str.padEnd(10, '0')); // Hello00000

大小写转换

String 类型提供了 toUpperCase() 和 toLowerCase() 方法用于将字符串转换为大写或小写。

以下示例演示了如何使用 toUpperCase() 和 toLowerCase() 方法:

String str = "Hello, world!";

System.out.println(str.toUpperCase()); // HELLO, WORLD!
System.out.println(str.toLowerCase()); // hello, world!

结语

String 类型是 Java 编程语言中表示文本数据的数据类型。本文介绍了 String 类型的一些常用 API,包括查询、拼接/截取、去空格、填充字符、大小写转换等。通过对这些 API 的了解和使用,您可以更加轻松地处理字符串数据,并编写出更加 robust 的代码。