Karthick
Karthick

Reputation: 193

How to Store the String Value in Char array in java..?

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.

Upvotes: 0

Views: 4842

Answers (5)

Chan
Chan

Reputation: 661

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

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

Upvotes: 0

Alexis C.
Alexis C.

Reputation: 93842

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);

Upvotes: 3

Harmlezz
Harmlezz

Reputation: 8068

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));
}

Upvotes: 1

Denis Kulagin
Denis Kulagin

Reputation: 8906

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);

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39457

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.

Upvotes: 1

Related Questions