I am relatively new to java programming. How would you split following lines of Strings separated by semicolons?
String; String; String; String, String; String;;String;
String; String; String; ;String;String;String;String
I would like to pass each String as an argument into a constructor (from txt file), but I am unable to find passable regex for the purpose. The constructor has 8 String arguments (from where there is nothing between two semicolons ;;
, I would like to get an empty String). In this case two separate objects would be created. I am aware of how splitting a String generally works but this one seems to be too tricky for me.
The issue is the
String.Split
does not keep the trailing empty elements:To include them, use
-1
as the second argument (see demo):See this Java reference:
Your answer is in the javadoc.
Since you stated that you want to contain the spaces, only split on the
;
and want to keep 8 arguments for your constructor, we are going to use the split with a limit method.String.split(String,int)
Example:
Gives:
What is only 7 in length and will fail your constructor.
Gives:
What is 8 in length and will work.
You can then address your constructor using: