java 字符串函数_Java字符串函数– 25+必须知道方法

java 字符串函数

Java字符串函数 (Java String Functions)

  • Java String class has a lot of functions to manipulate strings.

    Java String类具有许多操作字符串的功能。
  • There are many methods to get the characters and bytes of the string object.

    有很多方法可以获取字符串对象的字符和字节。
  • There are methods to split the string into an array or to create substrings.

    有一些方法可以将字符串拆分为数组或创建子字符串。
  • Since String is immutable, the original string remains unchanged and a new instance of string is returned.

    由于String是不可变的 ,因此原始字符串保持不变,并返回新的string实例。

Java字符串函数列表 (Java String Functions List)

Here is the list of most important String class functions. The list is updated for Java 13 release.

这是最重要的String类函数的列表。 该列表已针对Java 13版本进行了更新。

  • length()

    长度()
  • isEmpty(), isBlank()

    isEmpty(),isBlank()
  • charAt()

    charAt()
  • getChars(), toCharArray()

    getChars(),toCharArray()
  • getBytes()

    getBytes()
  • equals(), hashCode() and equalsIgnoreCase()

    equals(),hashCode()和equalsIgnoreCase()
  • contentEquals()

    contentEquals()
  • compareTo() and compareToIgnoreCase()

    compareTo()和compareToIgnoreCase()
  • startsWith() and endsWith()

    startsWith()和endsWith()
  • indexOf() and lastIndexOf()

    indexOf()和lastIndexOf()
  • substring() and subSequence()

    substring()和subSequence()
  • concat()

    concat()
  • matches()

    火柴()
  • replace(), replaceFirst(), and replaceAll()

    replace(),replaceFirst()和replaceAll()
  • contains()

    contains()
  • split()

    分裂()
  • join()

    加入()
  • toLowerCase() and toUpperCase()

    toLowerCase()和toUpperCase()
  • trim(), strip(), stripLeading(), and stripTrailing()

    trim(),strip(),stripLeading()和stripTrailing()
  • lines()

    lines()
  • indent()

    indent()
  • transform()

    转变()
  • format()

    格式()
  • intern()

    实习生()
  • valueOf() and copyValueOf()

    valueOf()和copyValueOf()
  • repeat()

    重复()
  • describeConstable() and resolveConstantDesc()

    describeConstable()和resolveConstantDesc()
  • formatted(), stripIndent(), and translateEscapes()

    formatted(),stripIndent()和translateEscapes()

Let’s look into these methods with simple code snippets running in JShell.

让我们用在JShell中运行的简单代码片段来研究这些方法。

1. length() (1. length())

String length() method returns the length of the string object.

String length()方法返回字符串对象的长度。

jshell> String s = "Hello Java";
s ==> "Hello Java"
 
jshell> s.length()
$2 ==> 10

2. isEmpty(),isBlank() (2. isEmpty(), isBlank())

String isEmpty() method returns True if the string is empty i.e. length is 0.

如果字符串为空,即长度为0,则String isEmpty()方法返回True。

String isBlank() method was added to the String class in Java 11 release. This method returns True if the string is empty or contains only whitespace characters such as spaces and tabs.

Java 11版本中 ,将String isBlank()方法添加到String类中。 如果字符串为空或仅包含空格字符(例如空格和制表符),则此方法返回True。

jshell> String emptyStr = "";
emptyStr ==> ""
 
jshell> String whitespacesStr = " \t\t ";
whitespacesStr ==> " \t\t "
 
jshell> emptyStr.isEmpty()
$5 ==> true
 
jshell> whitespacesStr.isEmpty()
$6 ==> false
 
jshell> emptyStr.isBlank()
$7 ==> true
 
jshell> whitespacesStr.isBlank()
$8 ==> true

3. charAt(int index) (3. charAt(int index))

This method returns the character at the given index. If the index is out of range, StringIndexOutOfBoundsException is thrown.

此方法返回给定索引处的字符。 如果索引超出范围,则抛出StringIndexOutOfBoundsException

jshell> String s = "Java";
s ==> "Java"
 
jshell> s.charAt(2)
$10 ==> 'v'
 
jshell> s.charAt(20)
|  Exception java.lang.StringIndexOutOfBoundsException: String index out of range: 20
|        at StringLatin1.charAt (StringLatin1.java:48)
|        at String.charAt (String.java:709)
|        at (#11:1)

4. getChars()和toCharArray() (4. getChars() and toCharArray())

String getChars() method is used to populate a character array from the string object as source. The method syntax is:

String getChars()方法用于从字符串对象中填充字符数组作为源。 方法语法为:

getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
  1. The srcBegin parameter is the index of the first character to copy from the string.

    srcBegin参数是要从字符串中复制的第一个字符的索引。
  2. The srcEnd is the index after the last character in the string to copy.

    srcEnd是要复制的字符串中最后一个字符之后的索引。
  3. The dst[] is the destination character array.

    dst []是目标字符数组。
  4. The dstBegin parameter is the offset index in the destination char array.

    dstBegin参数是目标char数组中的偏移量索引。
jshell> String s1 = "12345678";
s1 ==> "12345678"
 
jshell> char[] dest = new char[5];
dest ==> char[5] { '\000', '\000', '\000', '\000', '\000' }
 
jshell> s1.getChars(2, 5, dest, 1)
 
jshell> System.out.println(Arrays.toString(dest));
[, 3, 4, 5, ]

Java String toCharArray() method returns a new character array created from the string characters.

Java String toCharArray()方法返回从字符串字符创建的新字符数组。

jshell> String s2 = "12345";
s2 ==> "12345"
 
jshell> s2.toCharArray()
$28 ==> char[10] { '1', '2', '3', '4', '5' }

5. getBytes() (5. getBytes())

This method returns byte array created from the string. There are three versions of getBytes() method.

此方法返回从字符串创建的字节数组 。 getBytes()方法有三种版本。

  1. getBytes(): this method decode the bytes using the system default character set encoding.

    getBytes() :此方法使用系统默认字符集编码对字节进行解码。
  2. getBytes(Charset charset): The character set is used to decode the bytes.

    getBytes(Charset charset) :字符集用于解码字节。
  3. getBytes(String charsetName): The charsetName is used to get the actual Charset instance for decoding. If the charset is invalid, UnsupportedEncodingException is thrown.

    getBytes(String charsetName) :charsetName用于获取实际的Charset实例以进行解码。 如果字符集无效,则抛出UnsupportedEncodingException
jshell> String s3 = "Hello";
s3 ==> "Hello"
 
jshell> s3.getBytes();
$21 ==> byte[5] { 72, 101, 108, 108, 111 }
 
jshell> import java.nio.charset.StandardCharsets;
 
jshell> s3.getBytes(StandardCharsets.UTF_16);
$22 ==> byte[12] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111 }
 
jshell> s3.getBytes("UTF-16");
$23 ==> byte[12] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111 }
 
jshell> s3.getBytes("UTF-8");
$24 ==> byte[5] { 72, 101, 108, 108, 111 }

6. equals(),hashCode()和equalsIgnoreCase() (6. equals(), hashCode() and equalsIgnoreCase())

String equals(Object obj) method returns true if and only if the object is a string and represents the same sequence of characters as this string.

当且仅当对象是字符串并且表示与此字符串相同的字符序列时,字符串equals(Object obj)方法返回true。

The equals() method is being overridden from the Object class. The equals() method is used in Hashtable implementations.

从Object类重写equals()方法。 Hashtable实现中使用equals()方法。

jshell> String s4 = "Hello"
s4 ==> "Hello"
 
jshell> s4.equals(new Object())
$26 ==> false
 
jshell> s4.equals("Hello")
$28 ==> true

The hashCode() method returns the integer hash value of the string object. It’s cached when the string is created.

hashCode()方法返回字符串对象的整数哈希值。 创建字符串时将对其进行缓存。

The formula to calculate the hash code is given below.

下面给出了计算哈希码的公式。

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

Here s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation.

这里s [i]是字符串的第i个字符,n是字符串的长度,^表示幂。

jshell> String s = "Java"
s ==> "Java"
 
jshell> s.hashCode()
$30 ==> 2301506
 
jshell> String s2 = "Java"
s2 ==> "Java"
 
jshell> s2.hashCode()
$32 ==> 2301506
 
jshell> "String".hashCode()
$33 ==> -1808118735

If you are wondering why the hashCode() value is negative, it’s because the value returned from the formula is larger than the maximum value of the integer. So it’s causing integer overflow and in that case, the hashcode can be negative.

如果您想知道为什么hashCode()值为负,那是因为从公式返回的值大于整数的最大值。 因此,这会导致整数溢出,在这种情况下,哈希码可以为负数。

String equalsIgnoreCase(String str) compares this string with the given string, ignoring case considerations.

字符串equalsIgnoreCase(String str)将此字符串与给定的字符串进行比较,而忽略大小写考虑。

jshell> "Java".equalsIgnoreCase("JAVA")
$35 ==> true
 
jshell> "Java".equalsIgnoreCase("JA")
$36 ==> false

7. contentEquals() (7. contentEquals())

This String method compares the content of the string with the CharSequence object. It’s used to compare the string with the StringBuilder and StringBuffer object values.

此String方法将字符串的内容与CharSequence对象进行比较。 它用于将字符串与StringBuilderStringBuffer对象的值进行比较。

jshell> String str = "12345"
str ==> "12345"
 
jshell> StringBuffer sb = new StringBuffer()
sb ==> 
 
jshell> sb.append("12345")
$38 ==> 12345
 
jshell> str.contentEquals(sb)
$39 ==> true
 
jshell> StringBuilder sb1 = new StringBuilder(sb)
sb1 ==> 12345
 
jshell> str.contentEquals(sb1)
$41 ==> true

8. compareTo()和compareToIgnoreCase() (8. compareTo() and compareToIgnoreCase())

String implements Comparable interface. So, we can compare two strings lexicographically using the compareTo() method.

字符串实现Comparable接口 。 因此,我们可以使用compareTo()方法按字典顺序比较两个字符串。

The compareToIgnoreCase() method also performs the lexicographical comparison, ignoring case.

compareToIgnoreCase()方法还执行字典比较,而忽略大小写。

jshell> "Java".compareTo("Java")
$42 ==> 0
 
jshell> "Java".compareTo("Jb")
$43 ==> -1
 
jshell> "Java".compareToIgnoreCase("JAVA")
$44 ==> 0
 
jshell> "Java".compareToIgnoreCase("JB")
$45 ==> -1

9. startsWith()和endsWith() (9. startsWith() and endsWith())

These methods are used to check if the string has given prefix or suffix strings or not. The startsWith() has an overloaded method to provide the integer value as the offset index.

这些方法用于检查字符串是否具有给定的前缀或后缀字符串。 startsWith()有一个重载方法来提供整数值作为偏移索引。

jshell> "123456".startsWith("123")
$46 ==> true
 
jshell> "123456".startsWith("34")
$47 ==> false
 
jshell> "123456".startsWith("34", 2)
$48 ==> true
 
jshell> "123456".endsWith("456")
$49 ==> true
 
jshell> "123456".endsWith("45")
$50 ==> false

10. indexOf()和lastIndexOf() (10. indexOf() and lastIndexOf())

There are four overloaded indexOf() methods in String class.

String类中有四个重载的indexOf()方法。

  1. indexOf(int ch): returns the first index of the character in the string. If the character is not present, then returns -1.

    indexOf(int ch):返回字符串中字符的第一个索引。 如果不存在该字符,则返回-1。
  2. indexOf(int ch, int fromIndex): the second parameter specifies the index from where to search for the character.

    indexOf(int ch,int fromIndex):第二个参数指定从何处搜索字符的索引。
  3. indexOf(String str): returns the index of the first occurrence of the substring.

    indexOf(String str):返回第一次出现的子字符串的索引。
  4. indexOf(String str, int fromIndex): returns the index of the first occurrence of the substring starting from the given index.

    indexOf(String str,int fromIndex):从给定索引开始,返回第一次出现的子字符串的索引。
jshell> "Java".indexOf('a')
$51 ==> 1
 
jshell> "Java".indexOf('a', 2)
$52 ==> 3
 
jshell> "Java".indexOf("av")
$53 ==> 1
 
jshell> "Java".indexOf("av", 2)
$54 ==> -1

Similarly, there are four overloaded lastIndexOf() methods. The behavior is similar, except that the last index is returned. The search for the character or the substring starts from the end of the string.

同样,有四个重载的lastIndexOf()方法。 除了返回最后一个索引外,其行为类似。 搜索字符或子字符串从字符串的末尾开始。

  1. lastIndexOf(int ch)

    lastIndexOf(int ch)
  2. lastIndexOf(int ch, int fromIndex): the search is performed from backward, the returned index is between 0 and fromIndex.

    lastIndexOf(int ch,int fromIndex):从后向搜索,返回的索引在0到fromIndex之间。
  3. lastIndexOf(String str)

    lastIndexOf(String str)
  4. lastIndexOf(String str, int fromIndex)

    lastIndexOf(String str,int fromIndex)
jshell> "Java".lastIndexOf('a')
$55 ==> 3
 
jshell> "Java".lastIndexOf('a', 2)
$56 ==> 1
 
jshell> "Java".lastIndexOf("av")
$57 ==> 1
 
jshell> "Java".lastIndexOf("av", 3)
$58 ==> 1

11. substring()和subSequence() (11. substring() and subSequence())

Java String substring() method is used to create a substring from this string. The subSequence() method also creates a substring and internally calls the substring() method.

Java String substring()方法用于从该字符串创建子字符串。 subSequence()方法还会创建一个子字符串,并在内部调用substring()方法。

jshell> String str = "Java String"
str ==> "Java String"
 
jshell> str.substring(5)
$60 ==> "String"
 
jshell> str.substring(5, 8)
$61 ==> "Str"
 
jshell> str.subSequence(5, 8)
$62 ==> "Str"

12. concat() (12. concat())

String concat() method concatenates this string with the given string and returns it. The original string remains unchanged and a new string object reference is returned.

String concat()方法将此字符串与给定的字符串连接起来并返回它。 原始字符串保持不变,并返回新的字符串对象引用。

jshell> "Java".concat("String")
$63 ==> "JavaString"

13. matchs() (13. matches())

This method is used for regular expression pattern matching. If the string matches the given regex, it returns true.

此方法用于正则表达式模式匹配。 如果字符串与给定的正则表达式匹配,则返回true。

jshell> String str = "Java"
str ==> "Java"
 
jshell> str.matches("^J.v.")
$67 ==> true
 
jshell> str.matches("\\D{4}")
$68 ==> true

14. replace(),replaceFirst()和replaceAll() (14. replace(), replaceFirst(), and replaceAll())

These methods are used to replace part of the string with the given character or substring. There are four methods to replace string characters.

这些方法用于将字符串的一部分替换为给定的字符或子字符串。 有四种替换字符串字符的方法。

  1. replace(char oldChar, char newChar)

    替换(char oldChar,char newChar)
  2. replaceFirst(String regex, String replacement)

    replaceFirst(字符串正则表达式,字符串替换)
  3. replaceAll(String regex, String replacement)

    replaceAll(字符串正则表达式,字符串替换)
  4. replace(CharSequence target, CharSequence replacement)

    替换(CharSequence目标,CharSequence替换)

15. contains() (15. contains())

This method returns true if the string contains the given character sequence.

如果字符串包含给定的字符序列,则此方法返回true。

jshell> "Java".contains("av")
$69 ==> true
 
jshell> "Java".contains(new StringBuilder("Ja"))
$70 ==> true

16. split() (16. split())

This method is used to split the string around the matches of the given regex. There are two variations of this method.

此方法用于在给定正则表达式的匹配项附近拆分字符串。 此方法有两种变体。

  1. split(String regex, int limit): The limit parameter defines the number of records in the result string array.

    split(String regex,int limit):limit参数定义结果字符串数组中的记录数。
  2. split(String regex): returns the string array with all the substrings around the regex matches.

    split(String regex):返回带有正则表达式匹配项所有子字符串的字符串数组。

Recommended Reading: Java String split() Method

推荐阅读Java String split()方法

17. join() (17. join())

This static method was added to the String class in Java 8 release. It is used to concatenate a group of strings with the given delimiter to form a new string. It’s very useful in creating CSV string from a list or array of strings.

此静态方法已添加到Java 8版本的String类中。 它用于用给定的分隔符连接一组字符串以形成新的字符串。 从字符串列表或字符串数​​组创建CSV字符串非常有用。

jshell> String.join(",", "A", "B", "C");
$1 ==> "A,B,C"

Recommended Reading: Java String join() Method

推荐阅读Java String join()方法

18. toLowerCase()和toUpperCase() (18. toLowerCase() and toUpperCase())

These methods are used to create lowercase and uppercase strings from this string. There are overloaded methods to specify the Locale to be used for the conversion.

这些方法用于从该字符串创建小写和大写字符串。 有许多重载的方法来指定要用于转换的语言环境。

jshell> "Java".toUpperCase()
$71 ==> "JAVA"
 
jshell> "JavA".toLowerCase()
$72 ==> "java"
 
jshell> "Java".toUpperCase(Locale.US)
$73 ==> "JAVA"
 
jshell> "JavA".toLowerCase(Locale.UK)
$74 ==> "java"

Recommended Readings:

推荐读物

19. trim(),strip(),stripLeading()和stripTrailing() (19. trim(), strip(), stripLeading(), and stripTrailing())

Java String trim() method returns a new string after stripping all the leading and trailing whitespaces. This method considers any character whose codepoint is less than or equal to ‘U+0020’ as a whitespace character.

Java字符串trim()方法在剥离所有前导和尾随空格后返回一个新字符串。 此方法将代码点小于或等于“ U + 0020”的任何字符视为空白字符。

String strip() method was added to the String class in Java 11 release. This method uses Character.isWhitespace() method to remove leading and trailing whitespaces from a string. This is the recommended method to remove whitespaces from a string object.

Java 11版本中,String strip()方法已添加到String类。 此方法使用Character.isWhitespace()方法从字符串中删除开头和结尾的空格。 建议从字符串对象中删除空格的方法。

The stripLeading() and stripTrailing() methods remove leading and trailing whitespaces respectively.

stripLeading()和stripTrailing()方法分别删除前导和尾随空格。

jshell> String str = "  \t Hi  \t"
str ==> "  \t Hi  \t"
 
jshell> str.trim()
$76 ==> "Hi"
 
jshell> str.strip()
$77 ==> "Hi"
 
jshell> str.stripLeading()
$78 ==> "Hi  \t"
 
jshell> str.stripTrailing()
$79 ==> "  \t Hi"

Recommended Reading: Java 11: New Methods in String Class

推荐阅读Java 11:String类中的新方法

20. lines() (20. lines())

This method returns a stream of lines extracted from this string, separated by line terminators.

此方法返回从该字符串中提取的行流,以行终止符分隔。

jshell> String str = "Hi\nHello\nYes\r\nNo\n";
str ==> "Hi\nHello\nYes\r\nNo\n"
 
jshell> List lines = new ArrayList();
lines ==> []
 
jshell> str.lines().forEach(s -> lines.add(s));
 
jshell> System.out.println(lines);
[Hi, Hello, Yes, No]

21. indent() (21. indent())

This method is used to indent every line in the string and normalize the newline characters. It was added to String API in Java 12 release.

此方法用于缩进字符串中的每一行并规范换行符。 它已添加到Java 12发行版的String API中。

Recommended Reading: Java 12 String Methods

推荐读物: Java 12字符串方法

22. transform() (22. transform())

This method is used to apply a function to this string. The function should accept a single string argument and return an object. Some of the real-world usages are to create a list of strings from a CSV string and transforming a string to a list of objects. This utility method was added to String API in Java 12 release.

此方法用于将函数应用于此字符串。 该函数应接受单个字符串参数并返回一个对象。 某些实际用法是从CSV字符串创建字符串列表,并将字符串转换为对象列表。 此实用程序方法已添加到Java 12版本中的String API。

23. format() (23. format())

Java String format() method returns a formatted string using the given format and the arguments. It’s inspired by the C language sprintf() method.

Java String format()方法使用给定的格式和参数返回格式化的字符串。 它受C语言sprintf()方法的启发。

24. intern() (24. intern())

This method returns the canonical representation of the string. It’s a native method. When a string is created using new operator, it gets created outside the string pool. The intern() method moves the string to the pool and returns the reference.

此方法返回字符串的规范表示形式。 这是一种本地方法。 使用new运算符创建字符串时,它将在字符串池之外创建。 intern()方法将字符串移到池中并返回引用。

Recommended Reading: Java String intern() Method

推荐读物: Java String intern()方法

25. valueOf()和copyValueOf() (25. valueOf() and copyValueOf())

Java String valueOf() method is used to get the string representation of the argument. There are various overloaded valueOf() methods that accept primitive data types, char array, and object. The String valueOf() methods are static.

Java String valueOf()方法用于获取参数的字符串表示形式。 有许多重载的valueOf()方法可以接受原始数据类型,char数组和对象。 字符串valueOf()方法是静态的。

26. repeat() (26. repeat())

Java String repeat() method returns a new string whose value is the concatenation of this string given number of times. This method was added to the String class in Java 11 release.

Java String repeat()方法返回一个新字符串,该字符串的值是给定次数的此字符串的串联。 此方法已添加到Java 11发行版的String类中。

jshell> String str = "123"
str ==> "123"

jshell> str.repeat(3)
$9 ==> "123123123"

27. describeConstable()和resolveConstantDesc() (27. describeConstable() and resolveConstantDesc())

These methods are added to support Constants’ API for the String class. These methods were added to the String class in Java 12 release.

添加这些方法是为了支持String类的Constants API。 这些方法已添加到Java 12版本的String类中。

jshell> String s = "Hi"
s ==> "Hi"
 
jshell> s.describeConstable()
$85 ==> Optional[Hi]
 
jshell> import java.lang.invoke.MethodHandles;
 
jshell> s.resolveConstantDesc(MethodHandles.lookup());
$87 ==> "Hi"

Reference: Java 13 String API Docs

参考Java 13字符串API文档

翻译自: https://www.journaldev.com/33358/java-string-functions-methods

java 字符串函数

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值