Split given string or sentence word by word and display in an Array or an ArrayList
package abc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner
scnr = new Scanner(System.in);
System.out.println("Enter the string");//There are 7 days in a week.
String
inputString = scnr.nextLine();
String[]
splitString = inputString.split(" ");
System.out.println("In Array :"+Arrays.toString(splitString));//In Array :[There, are, 7, days, in, a, week.]
int arrayLength = splitString.length;
ArrayList<String>
alist = new ArrayList<>();
for(int i=0;i<arrayLength;i++) {
alist.add(splitString[i]);
}
System.out.println("In ArrayList : "+alist);//In
ArrayList : [There, are, 7, days, in, a, week.]
}
}
Output:
Enter the string
There are 7 days in a week.
In Array :[There, are, 7, days, in,
a, week.]
In ArrayList : [There, are,
7, days, in, a, week.]
No comments:
Post a Comment