JAVA朗,弦。Java中的copyValueOf()

copyValueOf()主要是 副本 将字符数组的内容转换为字符串。该函数有两种变体,本文将讨论这两种变体。 实施1:

null
Syntax:
public static String copyValueOf(char[] ch)
Parameters:
ch : The character array.
Return Value : 
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:

Syntax:
public static String copyValueOf(char[] ch, int index, int num)
Parameters:
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. 
Return Value : 
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( "" );
// 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

本文由 阿斯塔·蒂亚吉 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享