Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting char array of particular length into a string

Tags:

java

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?

like image 731
saranya Avatar asked Jan 13 '23 02:01

saranya


2 Answers

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 );
like image 173
Steve Avatar answered Jan 30 '23 23:01

Steve


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);
like image 24
Se Won Jang Avatar answered Jan 30 '23 23:01

Se Won Jang