How to Parse a String in Java
Parsing is a term used by computer programmers to describe the act of splitting a sequence of text (also called a string) into multiple, smaller strings based on some delimiter. For example, a Java program might use a text file to store configuration data, where each configurable item is separated by a semicolon. This text file can be parsed into multiple strings using the semicolon as a delimiter. Parsing text is a common application of computer software. If you are a beginner to Java programming, the sooner you learn how to parse strings the better.
Things You'll Need
- Java Software Development Kit with NetBeans Integrated Development Environment (IDE) Bundle (see Resources)
Instructions
-
-
1
Load the NetBeans IDE by clicking on its program icon. When the program loads, navigate to "New/New Project" and select "Java Application" from the list on the right-hand side of the screen. A new source code file appears in the NetBeans text editor. The source code file contains an empty main method.
-
2
Write the following string declaration in between the curly brackets that immediately follow the main method:
String shoppingList = "Tomato, Apple, Avocado, Milk, Eggs";
-
-
3
Split the string apart using the comma as the delimiter. This is accomplished using the "split" function. The output of this function is an array, or sequence, of strings. Declare a new array of strings and use the "split" function in one line of code, like this:
String[] individualItems = shoppingList.split("[,]+");
-
4
Iterate through the array of strings and print the value of each to the output window. Accomplish this by writing a for loop, like this:
for(int i = 0; i < individualItems.length; i++)
{System.Out.Println(individualItems[i]);}
-
5
Execute the program by pressing the "F6" key. The program output looks like this:
Tomato
Apple
Avocado
Milk
Eggs
-
1