StringIndexOutOfBoundsException when using delimiter - java

I want to split a string into multiple parts based on parentheses. So if I have the following string:
In fair (*NAME OF A CITY), where we lay our (*NOUN),
The string should be split as:
In fair
*NAME OF A CITY
, where we lay our
*NOUN
I set up a delimiter like so:
String delim = "[()]";
String [] inputWords = line.split (delim);
Because the strings in all caps with an * at the beginning are going to be replaced with user input, I set up a loop like so:
while (input.hasNextLine())
{
line = input.nextLine();
String [] inputWords = line.split (delim);
for (int i = 0; i < inputWords.length; i++)
{
if (inputWords[i].charAt(0) != '*')
{
newLine.append (inputWords[i]);
}
else
{
String userWord = JOptionPane.showInputDialog (null, inputWords[i].substring (1, inputWords[i].length()));
newLine.append (userWord);
}
}
output.println (newLine.toString());
output.flush();
newLine.delete (0, line.length());
}
Looks like I'm getting an error with this if statement:
if (inputWords[i].charAt(0) != '*')
When I run it, I get a StringIndexOutOfBoundsException: String index out of range: 0. Not sure why that's happening. Any advice? Thank you!

apparently line = input.nextLine(); gives you a blank string, as #Marco already mentioned.
handle empty line(s) before processing further.

Related

Detect and replace unpaired markdown symbols, not changing paired symbols

I have this
Hello \**how are you\**? I'm fine*
need to get this
Hello *how are you*? I'm fine\*
I can get
Hello *how are you*? I'm fine*
but then I'm lost, since s.replace("*', "\*") is not an option
Basically the problem is about the matching (paired) * needing to be replaced with *, while unpaired * needing to be escaped.
The basic idea is to split the string in words, then find out which words have unpaired '*'.
String text1 = "*This* is **my** text*";
String[] words = text1.split(" ");
for(int i=0; i<words.length; i++){
int count = words[i].length() - words[i].replace("*", "").length(); // count the number of '*'
if(count%2 != 0){ // if it's not paired we can replace with '\*'
words[i] = words[i].replace("*", "\\*");
}
}
System.out.println(String.join(" ", words));
Which prints out: *This* is **my** text\*
Someone helped me out with this:
String text1 = "*This is **my** text* ";
System.out.println(text1.replaceAll("(?<=[^*\\\\]|\\A)[*](?=[^*\\\\]|\\z)", "\\\\*"));
which prints \*This is **my** text\*

Spliting String into sections with keywords

I have a String i read from a .txt file with has values in sections seperated like
Text first
[section_name_1]
Text with values pattern1
...
[section_name_2]
Text with values pattern2
I need to split the sections at the section_name_# marks and add those to a String [] (Size of the array is fixed). My Code by now does not make some weird output:
//Code:
public static String[] parseFileToParams(File file)
{
String[] sections= {"[section_name_1]","[section_name_2]","[section_name_3]","[section_name_4]"};
String[] params = new String[sections.length+1];
StringBuilder sb = new StringBuilder();
String decoded = parseFile(file);// Returns the Text from the file
for(int i=0; i< sections.length;i++)
{
params[i]= decoded.split(sections[i])[1];
sb.append(params[i]);
}
return params;
}
//For Test of the output
String[] textArray = BasicOsuParser.parseFileToParams(parseFile);
for(int j = 0; j<textArray.length;j++)
{
sb.append(textArray[j]);
}
String text= sb.toString();
System.out.println (text); //Output: su f form formau fnull
// Obviously not how it should look like
Thanks for help!
Try this:
String[] sections= {"[section_name_1]","[section_name_2]","[section_name_3]","[section_name_4]"};
String textFromFile = "Text first [section_name_1] Text with values pattern1 [section_name_2] Text with values pattern2";
int count = 0;
for(int i = 0; i < sections.length; i++){
if(textFromFile.contains(sections[i])){//Use this to tell how big the parms array will be.
count++;
}
sections[i] = sections[i].replace("[", "\\[").replace("]", "\\]");//Removes the brackets from being delimiters.
}
String[] parms = new String[count+1];//Where the split items will go.
int next = 0;//The next index for the parms array.
for(String sec : sections){
String split[] = textFromFile.split(sec);//Split the file's text by the sec
if(split.length == 2){
parms[next] = split[0];//Adds split to the parms
next++;//Go to the next index for the parms.
textFromFile = split[1];//Remove text which has just been added to the parms.
}
}
parms[next] = textFromFile;//Add any text after the last split.
for(String out : parms){
System.out.println(out);//Output parms.
}
This will do what you have asked and it is commented so you can see how it works.
It's not a good idea use split() only for a one delimiter in text. This method tries to separate the text by given regexp pattern and usually used where there are more than one given delimiter in the text. Also you should screen special symbols in reqexp like '.','[' and so on. read about patterns in java. In your case better use substring() and indexOf():
public static String[] parseFileToParams(File file)
{
String[] sections= {"[section_name_1]","[section_name_2]","[section_name_3]","[section_name_4]"};
String[] params = new String[sections.length+1];
String decoded = parseFile(file);// Returns the Text from the file
int sectionStart = 0;
for (int i = 0; i < sections.length; i++) {
int sectionEnd = decoded.indexOf(sections[i], sectionStart);
params[i] = decoded.substring(sectionStart, sectionEnd);
sectionStart = sectionEnd + sections[i].length();
}
params[sections.length] = decoded.substring(sectionStart, decoded.length());
return params;
}
params[i]= decoded.split(sections[i])[1];
This returns the string after the first appearance of the sections[i] i.e. not just until the section[i+1] but till the end of file.
This loop,
for(int i=0; i< sections.length;i++)
{
params[i]= decoded.split(sections[i])[1];
sb.append(params[i]);
}
return params;
Repeatedly splits decoded into 2 halves, separated by the given section. You then append the entire 2nd half into params.
Example, pretend you wanted to split the string "abcdef" along "a", "b", etc.
You would split along a, and append "bcdef" to params, then split along b, and append "cdef" to params, etc., so you would get "bcdefcdef...f".
I think what you want to do is use real regex as the delimiter, something like params = decoded.split([section_name_.]). Look at http://www.tutorialspoint.com/java/java_string_split.htm and https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx
and if you want t

Inserting Newline character before every number occurring in a string?

I have String of format something like this
String VIA = "1.NEW DELHI 2. Lucknow 3. Agra";
I want to insert a newline character before every digit occurring succeeded a dot so that it final string is like this
String VIA = "1.NEW DELHI " +"\n"+"2. Lucknow " +"\n"+"3. Agra";
How can I do it. I read Stringbuilder and String spilt, but now I am confused.
Something like:
StringBuilder builder = new StringBuilder();
String[] splits = VIA.split("\d+\.+");
for(String split : splits){
builder.append(split).append("\n");
}
String output = builder.toString().trim();
The safest way here to do that would be go in a for loop and check if the char is a isDigit() and then adding a '\n' before adding it to the return String. Please note, I am not sure if you want to put a '\n' before the first digit.
String temp = "";
for(int i=0; i<VIA.length(); i++) {
if(Character.isDigit(VIA.charAt(i)))
temp += "\n" + VIA.charAt(i);
} else {
temp += VIA.charAt(i);
}
}
VIA = temp;
//just use i=1 here of you want to skip the first charachter or better do a boolean check for first digit.

Separate one String with ',' character into two new String

A MySQL table called item_list has a field named description, the problem is the previous programmer combined the name and description of the item in one field called description. The data is now at 20k+. Now I am going to have a problem during migration.So how do I separate one
String description="BEARING, ROLLER 23230CKE4 SPHERICAL"
into two new strings
String name="BEARING"
String description="ROLLER 23230CKE4 SPHERICAL"
Any help will be appreciated.
you can try this way
String description="BEARING, ROLLER 23230CKE4 SPHERICAL";
String [] arr=description.split(",");
System.out.println(arr[0]);
System.out.println(arr[1]);
output
BEARING
ROLLER 23230CKE4 SPHERICAL
String Split methods returns an array of strings.As in the String description has one comma(,) So the whole string will be splited into 2 strings.
You can use StringTokenizer
something like this
StringTokenizer st = new StringTokenizer(description,",");
String name=st.nextToken();
description=st.nextToken();
Unfortunately string split functions will not work correctly if there is more than 1 , in the combined string.
I recommend you split on the first , only.
int idx = description.indexOf(',');
if (idx != -1) { // if there is a comma
name = description.substring(0, idx);
description = description.substring(idx+1);
} else {
???? // no comma in description
}
combination of all the answers.., that solve the problem.
String name="",new_d ="";
String description="BEARING, ROLLER 23230CKE4 SPHERICAL";
int idx = description.indexOf(',');
if (idx != -1) { // if there is comma
String arr[]=description.split(",\\s*");
name=arr[0].toString();
new_d=arr[1].toString();
}
else {
// if there is no comma
name=description;
new_d="";
}
System.out.println(name);
System.out.println(new_d);

Checking whether the String contains multiple words

I am getting the names as String. How can I display in the following format: If it's single word, I need to display the first character alone. If it's two words, I need to display the first two characters of the word.
John : J
Peter: P
Mathew Rails : MR
Sergy Bein : SB
I cannot use an enum as I am not sure that the list would return the same values all the time. Though they said, it's never going to change.
String name = myString.split('');
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
String finalName = topTitle + finalName;
The above code fine, but its not working. I am not getting any exception either.
There are few mistakes in your attempted code.
String#split takes a String as regex.
Return value of String#split is an array of String.
so it should be:
String[] name = myString.split(" ");
or
String[] name = myString.split("\\s+);
You also need to check for # of elements in array first like this to avoid exception:
String topTitle, subTitle;
if (name.length == 2) {
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
}
else
topTitle = name.subString(0,1);
The String.split method split a string into an array of strings, based on your regular expression.
This should work:
String[] names = myString.split("\\s+");
String topTitle = names[0].subString(0,1);
String subTitle = names[1].subString(0,1);
String finalName = topTitle + finalName;
First: "name" should be an array.
String[] names = myString.split(" ");
Second: You should use an if function and the length variable to determine the length of a variable.
String initial = "";
if(names.length > 1){
initial = names[0].subString(0,1) + names[1].subString(0,1);
}else{
initial = names[0].subString(0,1);
}
Alternatively you could use a for loop
String initial = "";
for(int i = 0; i < names.length; i++){
initial += names[i].subString(0,1);
}
You were close..
String[] name = myString.split(" ");
String finalName = name[0].charAt(0)+""+(name.length==1?"":name[1].charAt(0));
(name.length==1?"":name[1].charAt(0)) is a ternary operator which would return empty string if length of name array is 1 else it would return 1st character
This will work for you
public static void getString(String str) throws IOException {
String[] strr=str.split(" ");
StringBuilder sb=new StringBuilder();
for(int i=0;i<strr.length;i++){
sb.append(strr[i].charAt(0));
}
System.out.println(sb);
}

Categories

Resources