在本指南中,我们将通过一个例子学习所有字符串类的API/方法。本指南根据Java 11中新增的字符串API进行了更新,并附有一个例子。
以下是Java 11中添加到String类的API/方法。
正如我们所知,字符串在Java编程中被广泛使用,是一串字符。在Java编程语言中,字符串是对象。
Java平台提供了java.lang.String类来创建和操作字符串。
###1.1 创建一个字符串对象
有两种方法可以创建一个字符串对象。
Java字符串字面意义是通过使用双引号创建的。
例如。
String s="javaguides";
每次你创建一个字符串字面,JVM首先检查字符串常量池。如果字符串已经存在于池中,就会返回一个对池中实例的引用。如果字符串不存在于池中,就会创建一个新的字符串实例并放入池中。
比如说
String s1="javaguides";
String s2="javaguides";
//will not create new instance
想知道更多关于字符串池的工作细节,请点击Guide to Java String Constant Pool。
现在的问题是,为什么java要使用字符串字面的概念?
很简单,为了使Java的内存效率更高(因为如果字符串常量池中已经存在,就不会再创建新对象)。
让我们创建一个简单的例子,通过使用new关键字创建String对象来演示。
public static void main(String[] args) {
String str = new String("Java Guides");
// create String object using new Keyword
int length = str.length();
System.out.println(" length of the string '" + str + "' is :: " + length);
}
输出:
length of the string 'Java Guides' is:: 11
从上面的例子中,JVM将在正常(非池)堆内存中创建一个新的字符串对象,字面意思 "Java Guides "将被放在字符串常量池中。变量str将指代堆(非池)中的对象。
要创建一个由字符数组初始化的字符串,下面是一个例子。
char chars[] = {
'a',
'b',
'c'
}
;
String s = new String(chars);
让我们通过实例探索所有的字符串API来深入学习字符串。
字符串类实现的接口。 Serializable, CharSequence, Comparable< String> 。 请参考java.lang.String上的更多细节。 JavaDoc.
字符串类实现的接口
字符串类支持几个构造函数。
String s = new String();
将创建一个没有任何字符的String实例。
char chars[] = {
'a',
'b',
'c'
}
;
String s = new String(chars);
这个构造函数用字符串 "abc "来初始化s。
String(char chars[], int startIndex, int numChars)
这里,startIndex指定了子范围开始的索引,numChars指定了要使用的字符数。下面是一个例子。
char chars[] = {
'a',
'b',
'c',
'd',
'e',
'f'
}
;
String s = new String(chars, 2, 3);
这就用字符的cde初始化了s。
String(String strObj)
这里,strObj是一个字符串对象。考虑一下这个例子。
// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {
'J',
'a',
'v',
'a'
}
;
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
这个程序的输出结果如下。
Java Java
你可以看到,s1和s2包含相同的字符串。
String(byte chrs[]) String(byte chrs[], int startIndex, int numChars)
这里,chris指定的是字节数组。第二种形式允许你指定一个子范围。在每个构造函数中,字节到字符的转换是通过使用平台的默认字符编码完成的。下面的程序说明了这些构造函数。
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {
65,
66,
67,
68,
69,
70
}
;
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
这个程序产生了以下输出:
ABCDEF CDE
String(StringBuffer strBufObj) String(StringBuilder strBuildObj)
例子。
String string = new String(new StringBuffer("JavaGuides"));
System.out.println(string);
String string2 = new String(new StringBuilder("JavaGuides"));
System.out.println(string2);
输出:
JavaGuides JavaGuides
要从一个字符串中提取单个字符,你可以通过charAt()方法直接引用单个字符。
例1: 返回这个字符串中指定索引处的char值。第一个char值在索引0处。
String str = "Welcome to string handling guide";
char ch1 = str.charAt(0);
char ch2 = str.charAt(5);
char ch3 = str.charAt(11);
char ch4 = str.charAt(20);
System.out.println("Character at 0 index is: " + ch1);
System.out.println("Character at 5th index is: " + ch2);
System.out.println("Character at 11th index is: " + ch3);
System.out.println("Character at 20th index is: " + ch4);
输出:
Character at 0 index is: W Character at 5th index is: m Character at 11th index is: s Character at 20th index is: n
例2:抛出IndexOutOfBoundsException - 如果索引参数是负数或者不小于这个字符串的长度。
String str = "Java Guides";
char ch1 = str.charAt(str.length() + 1);
System.out.println("character :: " + ch1);
输出:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12 at java.lang.String.charAt(String.java:658) at com.javaguides.strings.methods.ChatAtExample.charAtExample2(ChatAtExample.java:26) at com.javaguides.strings.methods.ChatAtExample.main(ChatAtExample.java:6)
例3:如何获得字符串的第一个和最后一个字符
String str = "Java Guides";
int strLength = str.length();
// Fetching first character
System.out.println("Character at 0 index is: " + str.charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: " + str.charAt(strLength - 1));
输出:
Character at 0 index is: J Character at last index is: s
该方法返回指定索引处的字符(Unicode代码点)。索引指的是char值(Unicode代码单位),范围从0到length()-1。
如果索引参数为负数或不小于该字符串的长度,该方法会抛出IndexOutOfBoundsException。
例子:
public class CodePointAtExample {
public static void main(String[] args) {
String str = "javaguides";
int unicode = str.codePointAt(0);
System.out.println("the character (Unicode code point) at the specified index is :: " + unicode);
}
}
输出:
the character (Unicode code point) at the specified index is:: 106
该方法返回指定索引之前的字符(Unicode代码点)。索引指的是char值(Unicode代码单位),范围从1到长度。
如果index参数为负数或不小于该字符串的长度,该方法会抛出IndexOutOfBoundsException。
例子:
public class CodePointBeforeExample {
public static void main(String[] args) {
String str = "javaguides";
int unicode = str.codePointBefore(1);
System.out.println("the character (Unicode code point)" + " at the before specified index is :: " + unicode);
}
}
输出:
the character (Unicode code point) at the before specified index is:: 106
该方法返回该字符串的指定文本范围内的Unicode代码点的数量。文本范围从指定的beginIndex开始,延伸到索引endIndex-1的字符。
如果beginIndex为负数,或者endIndex大于此字符串的长度,或者beginIndex大于endIndex,此方法会抛出IndexOutOfBoundsException。
例子。
public class CodePointCountExample {
public static void main(String[] args) {
String str = "javaguides";
System.out.println("length of the string :: " + str.length());
int unicode = str.codePointCount(0, str.length());
System.out.println("the character (Unicode code point) " + " at the specified index is :: " + unicode);
}
}
输出:
length of the string:: 10 the character (Unicode code point) at the specified index is:: 10
通常,仅仅知道两个字符串是否相同是不够的。对于排序应用,你需要知道哪一个小于、等于、或大于下一个。如果一个字符串在字典中的顺序在另一个之前,那么它就小于另一个。
如果一个字符串在字典中排在另一个字符串的后面,那么它就大于另一个字符串。compareTo()方法就是为了这个目的。它由Comparable interface指定,由String实现。它有这样的一般形式。
int compareTo(String str)
这里,str是被比较的字符串和调用的字符串。比较的结果以数值形式返回,意思是。
// A bubble sort for Strings.
public class CompareToSecondExample {
static String arr[] = {
"Now",
"is",
"the",
"time",
"for",
"all",
"good",
"men",
"to",
"come",
"to",
"the",
"aid",
"of",
"their",
"country"
}
;
public static void main(String args[]) {
for (int j = 0; j < arr.length; j++) {
for (int i = j + 1; i < arr.length; i++) {
if (arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
这个程序的输出是单词列表:
Now aid all come country for good is men of the the their time to to
从这个例子的输出可以看出,compareTo()考虑到了大写和小写字母。现在 "这个词在所有其他词之前出来,因为它以大写字母开头,这意味着它在ASCII字符集中的数值较低。
例子2: compareTo方法返回不同的值例子
String s1 = "Hello World";
String s2 = "Hello World";
String s3 = "Java";
String s4 = "Guides";
System.out.println(s1.compareTo(s2));
// 0 because both are equal
System.out.println(s1.compareTo(s3));
// -2 because "H" is 2 times lower than "J"
System.out.println(s1.compareTo(s4));
// 1 because "G" is 1 times greater than "H"
输出:
0 -2 1
**例子3:**使用compareTo()方法将字符串与黑色或空字符串进行比较。请注意,与空字符串比较会返回字符串的长度。
String s1 = "hello";
String s2 = "";
String s3 = "me";
// compare with empty string, returns length of the string
System.out.println(s1.compareTo(s2));
// If first string is empty, result would be negative
System.out.println(s2.compareTo(s3));
输出:
5 -2
对两个字符串进行按字母顺序的比较,忽略大小写差异。该方法返回一个整数,其符号为调用compareTo时的符号,其中每个字符的大小写差异已经通过调用Character.toLowerCase(Character.toUpperCase(character))消除。
例子。
String s1="Hello World";
String s2="hello world";
String s3="Java";
String s4="java";
System.out.println(s1.compareToIgnoreCase(s2));
System.out.println(s3.compareToIgnoreCase(s4));
输出:
0 0
如果指定的字符串大于、等于或小于该字符串,该方法返回一个负整数、零或正整数,忽略大小写的考虑。
将指定的字符串连接到这个字符串的末尾。
该方法创建一个新的对象,该对象包含调用的字符串,并将str的内容附加到结尾。 concat()执行的功能与+相同。
例子:
public class ConcatExmaple {
public static void main(String[] args) {
String str = "javaguides";
str = str.concat(".net");
System.out.println("Concatenates the specified string to the end of this string : " + str);
System.out.println("cares".concat("s"));
System.out.println("to".concat("get"));
}
}
输出:
Concatenates the specified string to the end of this string: javaguides.net caress toget
当且仅当这个字符串包含指定的char值序列时返回true。
示例:
public class ContainsExample {
public static void main(String[] args) {
String str = "javaguides";
boolean contains = str.contains("guides");
System.out.println("Contains : " + contains);
}
}
输出:
Contains: true
有两个版本的contentEquals方法。
contentEquals(CharSequence cs) - 将此字符串与指定的CharSequence进行比较。
contentEquals(StringBuffer sb) - 将此字符串与指定的StringBuffer进行比较。
例子:
public class ContentEqualsExample {
public static void main(String[] args) {
String str = "javaguides";
String subStr = "javaguides";
boolean isContentEquals = str.contentEquals(subStr);
System.out.println("isContentEquals :: " + isContentEquals);
isContentEquals = str.contentEquals(new StringBuffer(subStr));
System.out.println("isContentEquals :: " + isContentEquals);
}
}
输出:
isContentEquals:: true isContentEquals:: true
该方法测试该字符串是否以指定的后缀结束。如果参数所代表的字符序列是这个对象所代表的字符序列的后缀,则返回真;否则返回假。
例子。
public class EndsWithExample {
public static void main(String[] args) {
String str = "javaguides";
String subStr = "guides";
boolean endsWith = str.endsWith(subStr);
System.out.println(str + " endsWith " + subStr +" :: " + endsWith);
}
}
输出:
javaguides endsWith guides:: true
要比较两个字符串是否相等,使用equals()。它有这样的一般形式。
boolean equals(Object str)
这里,str是字符串对象与调用的字符串对象进行比较。如果两个字符串以相同的顺序包含相同的字符,则返回真,否则返回假。这种比较是区分大小写的。
要执行忽略大小写差异的比较,请调用 equalsIgnoreCase()。当它比较两个字符串时,它认为A-Z与a-z是一样的。它有这样的一般形式。
boolean equalsIgnoreCase(String str)
这里,str是字符串对象与调用的字符串对象进行比较。如果这两个字符串以相同的顺序包含相同的字符,它也会返回真,否则返回假。
下面是一个演示equals()和equalsIgnoreCase()的例子。
// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4));
}
}
程序的输出显示在这里:
Hello equals Hello ->
true Hello equals Good-bye ->
false Hello equals HELLO ->
false Hello equalsIgnoreCase HELLO ->
true
例2:
public class EqualsExample {
public static void main(String[] args) {
String str = "javaguides";
String str1 = "javaguides";
String str3 = "javatutorial";
boolean equal = str.equals(str1);
System.out.println(" Is both string are equal :: " + equal);
}
}
输出:
Is both string are equal:: true
例3:
public class EqualsIgnoreCaseExample {
public static void main(String[] args) {
String str = "javaguides";
boolean equal = str.equalsIgnoreCase("JAVAguides");
System.out.println("Strings are equal :: " + equal);
}
}
输出:
Strings are equal:: true
getBytes()方法有四个版本。有一个替代getChars()的方法,将字符存储在一个字节数组中。 byte[] getBytes() - 使用平台的默认字符集将此字符串编码为一串字节,将结果存储到一个新的字节数组中。
byte[] getBytes(Charset charset) - 使用给定的字符集将该字符串编码成一串字节,并将结果存储到一个新的字节数组中。
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) - 已废弃。
byte[] getBytes(String charsetName) - 使用指定的字符集将该字符串编码为一串字节,将结果存储到一个新的字节数组中。
让我们写一个例子来演示所有的getBytes()方法。
public class GetBytesExamples {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "javaguides";
// Encodes this String into a sequence of bytes using the platform's
// default charset, storing the result into a new byte array.
byte[] bs = str.getBytes();
for (byte b : bs) {
System.out.println(b);
}
// Encodes this String into a sequence of bytes using the given charset,
// storing the result into a new byte array.
byte[] bs1 = str.getBytes(Charset.forName("UTF-8"));
for (byte b : bs1) {
System.out.println(b);
}
// Encodes this String into a sequence of bytes using the given charset,
// storing the result into a new byte array.
byte[] bs2 = str.getBytes("UTF-8");
for (byte b : bs2) {
System.out.println(b);
}
byte[] dest = new byte[str.length()];
str.getBytes(0, str.length(), dest, 0);
for (byte b : dest) {
System.out.println(b);
}
}
}
如果你需要一次提取一个以上的字符,你可以使用getChars()方法。它有这样的一般形式。
void getChars(int sourceStart, int sourceEnd, char target[], int targetStart)
在这里,sourceStart指定了子串开始的索引,sourceEnd指定了所需子串结束后的一个索引。因此,子串包含从sourceStart到sourceEnd-1的字符。
接收这些字符的数组是由target指定的。子串在目标中被复制的索引在targetStart中被传递。必须注意确保目标数组足够大,以容纳指定子串中的字符数。
下面的程序演示了getChars()。
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
下面是这个程序的输出:
demo
返回这个字符串的哈希代码。字符串对象的哈希代码的计算方法是
s[0]/*31^(n-1) + s[1]/*31^(n-2) + ... + s[n-1]
使用int运算,其中s[i]是字符串的第i个字符,n是字符串的长度,^表示指数化。(空字符串的哈希值为零)。
例子。
public class HashcodeExample {
public static void main(String[] args) {
String str = "javaguides";
int hashcode = str.hashCode();
System.out.println("hashcode of " + str + " is :: " + hashcode);
}
}
输出:
hashcode of javaguides is:: -138203751
在java中有4种类型的indexOf方法。下面给出了indexOf方法的签名。
public class IndexOfExample {
public static void main(String[] args) {
String str = "javaguides";
// method 1
int index = str.indexOf("java");
System.out.println(index);
// Remember index starts with 0 so count from 0
System.out.println("index of guides :: " + str.indexOf("guides"));
System.out.println(" index of des :: " + str.indexOf("des"));
// method 2
System.out.println(str.indexOf('s'));
// method 3
System.out.println(str.indexOf('g', 0));
// method 4
System.out.println(str.indexOf("guides", 3));
}
}
输出:
0 index of guides:: 4 index of des:: 7 9 4 4
返回字符串对象的标准表示法。
一个字符串池,最初是空的,由String类私下维护。
例子。
public class InternExample {
public static void main(String[] args) {
String str = "javaguides";
String newStr = new String("javaguides");
System.out.println(newStr.intern().equals(str));
System.out.println(newStr.equals(str));
newStr.intern();
str.intern();
}
}
输出:
true true
java中的lastIndexOf方法有4种类型。LastIndexOf方法的签名如下。
例子。这个程序演示了所有4个lastIndexOf()方法的用法。
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "javaguides";
// method1
int lastIndexOf = str.lastIndexOf('s');
System.out.println(" last index of given character 's' in' " + " "+ str+"' :: " + lastIndexOf);
// method 2
lastIndexOf = str.lastIndexOf("guides");
System.out.println(" last index of given string 'guides' in' " + " "+ str+"' :: " + lastIndexOf);
// method 3
lastIndexOf = str.lastIndexOf("guides", 4);
System.out.println(" last index of guides in given string " + " "+ str+" and from index " + lastIndexOf);
// method 4
lastIndexOf = str.lastIndexOf('g', str.length());
System.out.println(" last index of given char :: " + lastIndexOf);
}
}
输出:
last index of given character 's' in' javaguides':: 9 last index of given string 'guides' in' javaguides':: 4 last index of guides in given string javaguides and from index 4 last index of given char:: 4
一个字符串的长度是它所包含的字符数。要获得这个值,可以调用length()方法,如下图所示。
int length()
例子。打印字符串 "Java Guides "的长度的例子。
public class LengthExample {
public static void main(String[] args) {
String str = new String("Java Guides");
int length = str.length();
System.out.println(" length of the string '" + str + "' is :: " + length);
}
}
输出:
length of the string 'Java Guides' is:: 11
regionMatches()方法有两种类型。
public class RegionMatchesExample {
public static void main(String[] args) {
String str = "javaguides";
String subStr = "guides";
boolean b = str.regionMatches(0, subStr, str.length(), str.length());
boolean b1 = str.regionMatches(true, 0, str, 0, str.length());
System.out.println(b);
System.out.println(b1);
}
}
输出:
false true
replace()方法有两种形式。第一种是用另一个字符替换调用字符串中所有出现的一个字符。它的一般形式如下。
String replace(char original, char replacement)
这里,original指定了要被替换掉的字符。结果字符串被返回。例如。
String s = "Hello".replace('l', 'w');
将字符串 "Hewwo "放入s。
replace()的第二种形式是将一个字符序列替换成另一个字符序列。它有这样的一般形式。
String replace(CharSequence original, CharSequence replacement)
例子。这是一个完整的例子,演示replace()方法的用法。
public class ReplaceExample {
public static void main(String[] args) {
String str = "javaguides";
String subStr = str.replace('a', 'b');
System.out.println("replace char 'a' with char 'b' from given string : " + subStr);
subStr = str.replace("guides", "tutorials");
System.out.println("replace guides with tutorials from given string : " + subStr);
subStr = str.replaceAll("[a-z]", "java");
System.out.println(subStr);
subStr = str.replaceFirst("[a-z]", "java");
System.out.println(subStr);
}
}
输出:
replace char 'a' with char 'b' from given string: jbvbguides replace guides with tutorials from given string: javatutorials javajavajavajavajavajavajavajavajavajava javaavaguides
将此字符串中与给定的正则表达式相匹配的每个子串替换为给定的替换。
例子。这是一个完整的例子来演示 replaceAll() 方法的用法。
public class ReplaceExample {
public static void main(String[] args) {
String str = "javaguides";
String subStr = str.replaceAll("[a-z]", "java");
System.out.println(subStr);
}
}
输出:
javajavajavajavajavajavajavajavajavajava
将此字符串中与给定的正则表达式相匹配的第一个子串替换为给定的替换。
例子。这是一个完整的例子来演示 replaceFirst() 方法的用法。
public class ReplaceExample {
public static void main(String[] args) {
String str = "javaguides";
String subStr = str.replaceFirst("[a-z]", "java");
System.out.println(subStr);
}
}
输出:
javaavaguides
有两种形式的split()方法。
例子。这是一个完整的例子来演示split()方法的用法。
public class SplitExample {
public static void main(String[] args) {
String str = "java,guides.net";
String[] strArray = str.split(",");
for (int i = 0;
i <
strArray.length;
i++) {
System.out.println(strArray[i]);
}
strArray = str.split(",", 0);
for (int i = 0;
i <
strArray.length;
i++) {
System.out.println(strArray[i]);
}
}
}
输出:
java guides.net java guides.net
startsWith()方法有两种形式。
例子。这是一个完整的例子来演示startsWith()方法的用法。
public class StartsWithExample {
public static void main(String[] args) {
String str = "javaguides";
boolean startWith = str.startsWith("ja");
System.out.println("startWith :: " +startWith);
// Remember index starts from 0
boolean startWithOffset = str.startsWith("guides", 4);
System.out.println("startWithOffset :: " + startWithOffset);
}
}
输出:
startWith:: true startWithOffset:: true
返回一个字符序列,它是这个序列的子序列。
调用此方法的形式为
str.subSequence(begin, end)
的调用,其行为与调用
str.substring(begin, end)
例子。这是一个完整的例子,演示subSequence()方法的用法。
public class SubSequenceExample {
public static void main(String[] args) {
String str = "javaguides";
CharSequence subStr = str.subSequence(0, str.length());
System.out.println("Returns a character sequence that " + " is a subsequence of this sequence : " + subStr);
}
}
输出:
Returns a character sequence that is a subsequence of this sequence: javaguides
substring()方法有两种形式。
例子。这是一个完整的例子来演示substring()方法的用法。
public class SubStringExample {
public static void main(String[] args) {
String str = "javaguides";
// substring from start to end
String subStr = str.substring(0, str.length());
System.out.println("substring from 0 to length of the string : " + subStr);
subStr = str.substring(4);
System.out.println("Sub string starts from index 4 : " + subStr);
// Remember index starts from 0
System.out.println(str.substring(1));
System.out.println("unhappy".substring(2));
System.out.println("Harbison".substring(3));
System.out.println("emptiness".substring(8));
}
}
输出:
substring from 0 to length of the string: javaguides Sub string starts from index 4: guides avaguides happy bison s
将这个字符串转换为一个新的字符数组。
例子。这是一个完整的例子,演示toCharArray()方法的用法。
public class ToCharArrayExample {
public static void main(String[] args) {
String str = "javaguides";
char[] characters = str.toCharArray();
for (char c : characters) {
System.out.println(c);
}
}
}
输出:
j a v a g u i d e s
有两种形式的toLowerCase()方法。
public class ToLowerCaseExample {
public static void main(String[] args) {
String str = "JAVAGUIDES";
String subStr = str.toLowerCase();
System.out.println(subStr);
subStr = str.toLowerCase(Locale.ENGLISH);
System.out.println(subStr);
}
}
输出:
javaguides javaguides
这个对象(已经是一个字符串了!)本身被返回。例子。
public class ToStringExample {
public static void main(String[] args) {
String str = "javaguides";
System.out.println(str.toString());
}
}
输出:
javaguides
有两种形式的toUpperCase()方法。
public class ToUpperCaseExample {
public static void main(String[] args) {
String str = "javaguides";
String subStr = str.toUpperCase();
System.out.println(subStr);
subStr = str.toUpperCase(Locale.ENGLISH);
System.out.println(subStr);
}
}
输出:
JAVAGUIDES JAVAGUIDES
返回一个字符串,其值是这个字符串,并去除任何前导和尾部的空白。
例子。这是一个完整的例子来演示trim()方法的用法。
public class TrimExample {
public static void main(String[] args) {
String str = "javaguides ";
String subStr = str.trim();
System.out.println("trim the space from given string : " + subStr);
}
}
输出:
trim the space from given string: javaguides
valueOf()方法将数据从其内部格式转换为人类可读的形式。
Java字符串valueOf()方法将不同类型的值转换为一个字符串。在string valueOf()方法的帮助下,你可以将int转换为字符串,long转换为字符串,布尔转换为字符串,字符转换为字符串,浮点转换为字符串,双倍转换为字符串,对象转换为字符串,char数组转换为字符串。
下面是它的几种形式,字符串valueOf()方法的签名或语法如下。
public static String valueOf(boolean b) public static String valueOf(char c) public static String valueOf(char[] c) public static String valueOf(int i) public static String valueOf(long l) public static String valueOf(float f) public static String valueOf(double d) public static String valueOf(Object o)
例子。让我们看一个例子,我们要把所有的基元和对象转换为字符串。
public class StringValueOfExample5 {
public static void main(String[] args) {
boolean b1=true;
byte b2=11;
short sh = 12;
int i = 13;
long l = 14L;
float f = 15.5f;
double d = 16.5d;
char chr[]= {
'j',
'a',
'v',
'a'
}
;
StringValueOfExample5 obj=new StringValueOfExample5();
String s1 = String.valueOf(b1);
String s2 = String.valueOf(b2);
String s3 = String.valueOf(sh);
String s4 = String.valueOf(i);
String s5 = String.valueOf(l);
String s6 = String.valueOf(f);
String s7 = String.valueOf(d);
String s8 = String.valueOf(chr);
String s9 = String.valueOf(obj);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);
System.out.println(s8);
System.out.println(s9);
}
}
输出:
true 11 12 13 14 15.5 16.5 java StringValueOfExample5@2a139a55
查看我的从初学者到专家的顶级Java String Tutorial。
**如果有任何建议,请发表评论,以改进这个字符串API指南,因为它对每个人都非常有用。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/08/java-string-class-api-guide.html
内容来源于网络,如有侵权,请联系作者删除!