Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove the first index of string array in Java?

I want to make this text below

String text = "  good morning  \t\thow  \n\nare you    today ";

become

[good, morning, how, are, you, today]

I have tried to split it using .split(["\\s+"]) but it still count the whitespace at the start of the text and store it to array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

String text = "  good morning  \t\thow \n\nare you today ";
String[] items = text.split("\\s+");
System.out.println("Items  = " + Arrays.toString(items));

This is the result I get

Items  = [, good, morning, how, are, you, today]

I have tried using items.remove(0) but the first index still can’t be removed. How to erase the first index?

>Solution :

Use trim() to remove the leading and trailing whitespace before splitting the string.

String text = "  good morning  \t\thow \n\nare you today ";
String[] items = text.trim().split("\\s+");
System.out.println("Items  = " + Arrays.toString(items));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading