copyValueOf()主要將字符數組的內容複製到字符串中。可以使用此函數的兩個變體,並且本文都會對此進行討論。實施1:
用法:
public static String copyValueOf(char[] ch)
參數:
ch:The character array.
返回值:
This function returns the string with the contents of character array copied
// Java code to demonstrate the working of
// copyValueOf implementation 1
public class Copy1 {
public static void main(String args[]) {
// Initialising Character array
char[] ch = {'A', 's', 't', 'h', 'a', ' ', 'T', 'y', 'a', 'g', 'i'};
// Initialising String
String ch2 = "";
// Copying value in ch2
// now ch2 is equal to "Astha Tyagi"
ch2 = ch2.copyValueOf( ch );
// Printing String
System.out.println("The new copied string is:" + ch2);
}
}
輸出:
The new copied string is:Astha Tyagi
在第二種實現中,也可以提取子數組而不是整個數組。
實施2:
用法:
public static String copyValueOf(char[] ch, int index, int num)
參數:
ch:The character array.
index: The starting position of array from which copy is to start.
num: Number of elements that has to be copied.
返回值:
This function returns the string with the contents of character array copied
// Java code to demonstrate the working of
// copyValueOf implementation 2
public class Copy2 {
public static void main(String args[]) {
// Initialising Character array
char[] ch = {'A', 's', 't', 'h', 'a', ' ', 'T', 'y', 'a', 'g', 'i'};
// Initialising String
String ch2 = "";
// Copying value in ch2
// only first 5 are extracted
// now ch2 is equal to "Astha"
ch2 = ch2.copyValueOf( ch , 0, 5 );
// Printing String
System.out.println("The new copied string is:" + ch2);
}
}
輸出:
The new copied string is:Astha
可能的應用:該函數可用於使用實現2從字符串中僅複製或提取前綴或後綴。一個可能的示例可以是僅從處理名稱的給定“ Rs 1000”類型的字符串中提取數量。
// Java code to demonstrate the application of
// copyValueOf
public class Appli2 {
public static void main(String args[]) {
// Initialising Character array
char[] ch = {'R', 's', ' ', '1', '0', '2', '4' };
// Original array
System.out.print("The original array is:");
for (int i=0; i< ch.length ; i++)
System.out.print(ch[i]);
System.out.print("\n");
// Initialising String
String ch2 = "";
// Copying value in ch2
// Rs is not included
// now ch2 is equal to "1024"
ch2 = ch2.copyValueOf( ch , 3, 4 );
// Printing String
System.out.println("The new string is:" + ch2);
}
}
輸出:
The original array is:Rs 1024 The new string is:1024
相關用法
- Java Java.util.concurrent.RecursiveTask用法及代碼示例
- Java Java lang.Long.numberOfTrailingZeros()用法及代碼示例
- Java Java lang.Long.lowestOneBit()用法及代碼示例
- Java Java.util.Collections.rotate()用法及代碼示例
- Java Java.util.concurrent.Phaser用法及代碼示例
- Java Java.util.concurrent.RecursiveAction用法及代碼示例
- Java Java.util.Collections.disjoint()用法及代碼示例
- Java Java.util.function.IntPredicate用法及代碼示例
- Java Java.util.function.LongPredicate用法及代碼示例
注:本文由純淨天空篩選整理自 Java.lang.String.copyValueOf() in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。