0

I have to Store the String value in fixed char array, i tried but after storing the value char array size changed depends upon the String Value... Can Any one tell me how to fix that issue..

char[] uniqueID = new char[10];
String lUniqueID = mUniqueIdTxtFld.getText();  
uniqueID = lUniqueID.toCharArray();

O/P:

lUniqueID=12D;     
 it show in uniqueID[1,2,D]... 

But i need [1,2,D,,,,,,,,]

(ie) fixed Char array, it should not change.. Any one suggestion me what is wrong on that.

6
  • char is a primitive type. A char array is filled with 0 by default. So, what you'll get is '1','2','D',0,0,0,0,0,0,0. Why would you want that? What are you trying to achieve? Commented Apr 24, 2014 at 11:26
  • thx for reply.. i want to store the string value with fixed size Commented Apr 24, 2014 at 11:29
  • That I understand. But why? What's the point? Commented Apr 24, 2014 at 11:30
  • that string value write in the file with fixed size. Commented Apr 24, 2014 at 11:34
  • So, why not write the string, and then use a loop to write the N missing blank characters? Commented Apr 24, 2014 at 11:36

5 Answers 5

3

The current problem is that when doing uniqueID = lUniqueID.toCharArray(); you are assigning a new char array to uniqueID and not the content of it into the previous array defined.

What you want to achieve can be done using Arrays.copyOf.

char[] uniqueID = Arrays.copyOf(lUniqueID.toCharArray(), 10);
Sign up to request clarification or add additional context in comments.

Comments

1

Use this method

System.arraycopy

and copy the chars from uniqueID = lUniqueID.toCharArray();
to some 10 chars long array arr which you created up-front.

1 Comment

A bit more cumbersome than the Arrays.copyOf hint by ZouZou, which also meets the "0s as padding" requirement.
1

You may try this:

public static void main(String arguments[]) {
    char[] padding = new char[10];
    char[] uniqueID = mUniqueIdTxtFld.getText().toCharArray();
    System.arraycopy(uniqueID, 0, padding, 0, Math.min(uniqueID.length, padding.length));
    System.out.println(Arrays.toString(padding));
}

1 Comment

This won't give 0s as padding in the target array, but ' 's instead.
0

Here is the snippet:

char[] uniqueID = new char[10];
String lUniqueID = mUniqueIdTxtFld.getText();
char[] compactUniqueID = lUniqueID.toCharArray();
System.arraycopy(compactUniqueID, 0, uniqueID, 0, compactUniqueID.length);

Comments

0

Have you tried the yourString.getChars(params) method?

    lUniqueId.getChars(0,uniqueID.length,uniqueID, 0);

Comments

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.