i need to convert char array into string , the problem in doing this is......i need to convert the character in char array of particular length say k to string. ie, char array is "b" .b takes value dynamically.....for instance take as "p,a,p,e,r,s" now k value also dynamic ,for this word "k=5" ,and then only 4 characters in char array "b" should be converted into string...ie the string should print as "paper"........ the code what i have now is
for(int c=0;c<=k;c++)
{
System.out.print(b[c]);
}
str=new String(b);
System.out.println(str);
where b[c]
prints correct value(in char array) as "paper". While converting to string str
(in program) it prints as "papers" itself....can anyone give me solution for this?
You can use a different constructor of String
that lets you specify the array along with the start point and number of characters to use.
In your case, you would try:
str = new String( b, 0, k );
char newArr[] = new char[k];
for (int i = 0; i < k; i++) {
newArr[i] = b[i];
System.out.print(b[i]); // print until the kth index
}
return new String(newArr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With