将特定长度的char数组转换为字符串

sar*_*nya 3 java

我需要将char数组转换为字符串,这样做的问题是......我需要将特定长度的字符数组中的字符转换为k到字符串.即,char数组是"b".b动态获取值.....例如取"p,a,p,e,r,s"现在k值也是动态的,对于这个单词"k = 5",然后char数组"b"中只有4个字符应转换为字符串...即字符串应打印为"paper"........我现在拥有的代码是

 for(int c=0;c<=k;c++)
 {
      System.out.print(b[c]);
 }
 str=new String(b);
 System.out.println(str); 
Run Code Online (Sandbox Code Playgroud)

其中将b[c]正确的值(在char数组中)打印为"paper".在转换为字符串str(在程序中)时,它打印为"论文"本身....任何人都可以给我解决方案吗?

Ste*_*eve 7

您可以使用不同的构造函数来String指定数组以及要使用的起点和字符数.

在你的情况下,你会尝试:

str = new String( b, 0, k );
Run Code Online (Sandbox Code Playgroud)