0

I have this simple code that split an input and put it in array of String:

Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    String[] arraySentence = s.split(" ");
    for (int i = 0; i<arraySentence.length; i++) {
        arraySentence[i].toCharArray();

        System.out.println(arraySentence[i].toCharArray());
    }

my focus is to manage every character of every single word into the array.

For example if I pass: "now we only have"

the string from input becomes: arraySentence{now, we, only, have} and I want to be able to take the "n" after the "o" then "w", etc.

How can do it? Thanks

2 Answers 2

1

Here's another way to achieve what you want to do.

public static void main(String[] args) {
     ArrayList<char[]> list = new ArrayList<>();

     String s = "now we only have";
     String[] arraySentence = s.split(" ");

     for(String str : arraySentence) {
         list.add(str.toCharArray());
     }

     list.forEach(arr -> System.out.println(Arrays.toString(arr)));
} 

list contains char arrays. Do whatever you want to do with them...

Output

[n, o, w]
[w, e]
[o, n, l, y]
[h, a, v, e]
Sign up to request clarification or add additional context in comments.

Comments

1

I hope I understood your question correctly, if not please leave a comment to be able to modify and correct. Inside your loop you can use the one of following snippet based on your needs.

char[] arr = arraySentence[i].toCharArray();
//in case you need n - o  - w
for(int i=0;i<arr.length;i++){
 System.out.print(arr[i]);
}

//also you can do this too 
for(char c: arr){
 System.out.print(arr[i]);
}
//in case you need w - o - n
for(int i=arr.length-1;i>=0;i--){
 System.out.print(arr[i]);
}

4 Comments

your loop is infinite, let me check better
which one exactly, :) the first or the second.. can you check updated answer
correct, thanks I was able to do that, but i forgot to put this instrution : System.out.print(arr[blu]+ " \n "); so I never see the correct result.
Great, would you please mark it as a valid and correct answer if it helped you

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.