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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。