本文共 17711 字,大约阅读时间需要 59 分钟。
java 字符串函数
Here is the list of most important String class functions. The list is updated for Java 13 release.
这是最重要的String类函数的列表。 该列表已针对Java 13版本进行了更新。
Let’s look into these methods with simple code snippets running in JShell.
让我们用在JShell中运行的简单代码片段来研究这些方法。
returns the length of the string object.
返回字符串对象的长度。
jshell> String s = "Hello Java";s ==> "Hello Java" jshell> s.length()$2 ==> 10
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 . This method returns True if the string is empty or contains only whitespace characters such as spaces and tabs.
在 ,将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
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)
is used to populate a character array from the string object as source. The method syntax is:
用于从字符串对象中填充字符数组作为源。 方法语法为:
getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
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' }
This method returns created from the string. There are three versions of getBytes() method.
此方法返回从字符串创建的 。 getBytes()方法有三种版本。
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 }
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 returns the integer hash value of the string object. It’s cached when the string is created.
返回字符串对象的整数哈希值。 创建字符串时将对其进行缓存。
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
This String method compares the content of the string with the CharSequence
object. It’s used to compare the string with the and object values.
此String方法将字符串的内容与CharSequence
对象进行比较。 它用于将字符串与和对象的值进行比较。
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
String implements . So, we can compare two strings lexicographically using the .
字符串实现 。 因此,我们可以使用字典顺序比较两个字符串。
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
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
There are four overloaded indexOf() methods in String class.
String类中有四个重载的indexOf()方法。
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()方法。 除了返回最后一个索引外,其行为类似。 搜索字符或子字符串从字符串的末尾开始。
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
method is used to create a substring from this string. The also creates a substring and internally calls the substring() method.
方法用于从该字符串创建子字符串。 还会创建一个子字符串,并在内部调用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"
concatenates this string with the given string and returns it. The original string remains unchanged and a new string object reference is returned.
将此字符串与给定的字符串连接起来并返回它。 原始字符串保持不变,并返回新的字符串对象引用。
jshell> "Java".concat("String")$63 ==> "JavaString"
This method is used for 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
These methods are used to replace part of the string with the given character or substring. There are four methods to characters.
这些方法用于将字符串的一部分替换为给定的字符或子字符串。 有四种字符的方法。
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
This method is used to split the string around the matches of the given regex. There are two variations of this method.
此方法用于在给定正则表达式的匹配项附近拆分字符串。 此方法有两种变体。
Recommended Reading:
推荐阅读 :
This static method was added to the String class in 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.
此静态方法已添加到版本的String类中。 它用于用给定的分隔符连接一组字符串以形成新的字符串。 从字符串列表或字符串数组创建CSV字符串非常有用。
jshell> String.join(",", "A", "B", "C");$1 ==> "A,B,C"
Recommended Reading:
推荐阅读 :
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:
推荐读物 :
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.
在剥离所有前导和尾随空格后返回一个新字符串。 此方法将代码点小于或等于“ U + 0020”的任何字符视为空白字符。
String strip() method was added to the String class in 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.
在版本中,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:
推荐阅读 :
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]
This method is used to indent every line in the string and normalize the newline characters. It was added to String API in release.
此方法用于缩进字符串中的每一行并规范换行符。 它已添加到发行版的String API中。
Recommended Reading:
推荐读物:
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。
returns a formatted string using the given format and the arguments. It’s inspired by the C language sprintf() method.
使用给定的格式和参数返回格式化的字符串。 它受C语言sprintf()方法的启发。
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:
推荐读物:
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.
用于获取参数的字符串表示形式。 有许多重载的valueOf()方法可以接受原始数据类型,char数组和对象。 字符串valueOf()方法是静态的。
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"
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 字符串函数
转载地址:http://qaqzd.baihongyu.com/