Reputation:
I need to store input1
input2
input3
in char array
of given same size.
public static void evalCharArray(int size){
System.out.println("please enter any three string not exceed than size"+size);
Scanner sc=new Scanner(System.in);
String input1=sc.nextLine();
String input2=sc.nextLine();
String input3=sc.nextLine();
//what i need is-I want to store these input string in three separate charArray of same length(ie of int size)
}
If i am using input1.toCharArray()
input2.toCharArray()
input3.toCharArray()
these are giving me array of different size based on input.
Upvotes: 1
Views: 487
Reputation: 14438
Use Arrays.copyOf(T[], int)
.
char[] input1=Arrays.copyOf(sc.nextLine().toCharArray(), size);
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.
Upvotes: 3
Reputation: 4692
You can use System.arraycopy()
method.
You can use this sample code.
public static void main(String[] args) {
String s = "work";
char[] arr = new char[10];
System.arraycopy(s.toCharArray(), 0, arr, 0, s.toCharArray().length );
System.out.println(arr.length); // prints 10
System.out.println(arr); // prints work
}
Upvotes: 3