4

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?

0

2 Answers 2

8

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 );
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for ur code...it worked when i give as str=new Stirng(b,0,k+1);
1
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);

3 Comments

thanks for this code.....but i need to print till k value...so i gave "i<=k".....but this is not working....(progarm is not running) .....y this happens so?
I've edited my answer. If you want to print until the kth index, then it should be i < k, since JAVA arrays are 0-indexed.
For example, if you have the word "papers", and you feed k = 6, it's not gonna run, since there is not index:6 for that string. Index:5 is the last index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.