I want to create a array from a text input:
Input 1: "car hat sun dog chair"
The input is separated by a "space"
My output in the array should be the position in the array.
Output in array list: [0 1 2 3 4]
So that 0=car 1=hat etc.
I want to create a array from a text input:
Input 1: "car hat sun dog chair"
The input is separated by a "space"
My output in the array should be the position in the array.
Output in array list: [0 1 2 3 4]
So that 0=car 1=hat etc.
I don't know why you are using an array here. You can maintain a hashpmap which contains a key value pair as below.
public static void main(String[] args) {
String input= "car hat sun dog chair";
String[] arr=input.split(" ");
for(int i=0;i<arr.length;i++){
Map<Integer, String> valueMap = new HashMap<Integer, String>();
System.out.print("================="+i+arr[i]);
valueMap.put(i, arr[i]);
}
}
The output 0car=================1hat=================2sun=================3dog=================4chair
Giving you the code would be counter-productive. Here's a thought that you can follow:
Problem: You have a String that you need to represent as an array (clubbing certain parts of it for each element of the array). The first thing you should ask is what a String is. From the java docs:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
See what's happening here, the String 'abc' is actually a sort of a concatenation obtained from a character array - data[]
. So, you can think of String as an character array with a representation that's easy on the eyes. Now, all you need to do is extract these characters one by one and put them neatly in an array. There are several ways of doing this. The String class provides you tons of convenient methods to achieve this in a few steps (single step too!).
Try a few things out, show us the code you wrote and we'll help you come along.
I suppose you need the below code.
String inpStr = "car hat sun dog chair";
String[] inpArr = inpStr.split(" ");
here the code which we do the needful to split the string with space
String inpStr = "car hat sun dog chair"; // request.getParameter("textName");
String[] inpArr = inpStr.split("\\s+"); // to split with " " we need to use regex for space \\s+
for (int j = 0; j < inpArr.length; j++) {
System.out.println(inpArr[j]);
}