Error when splitting a string - java

Im having this really weird issue that i haven't been able to figure out for a few hours. Basically im trying to split this getInterfaceBounds-client.ry, what im doing is this
final String className = line.split(".")[0];
im getting a arrayindexoutofbounds exception. I really have no idea why, do you?
Exception in thread "Thread-3" java.lang.ArrayIndexOutOfBoundsException: 0

split uses a regular expression. In regex . means any character, so you need to escape it.
Try:
final String className = line.split("\\.")[0];
See http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum

The change required is :
final String className = line.split("\\.")[0];
Check this example for more details.
String s="getInterfaceBounds-client.ry";
String[] arr = s.split("\\.");
for(String str : arr)
{
System.out.println(str);
}
Ideone link.

Use this instead and it will work. I just tested it.
String line = "getInterfaceBounds-client.ry";
String className = line.split("[.]")[0];
System.out.println(className);
The . is a special character in regex which represent any character.
You can learn more about the different special characters in regex here:
http://www.fon.hum.uva.nl/praat/manual/Regular_expressions_1__Special_characters.html

Use Array variable for split() beacuse we may get more than a value from splitting so it would be helpful if u use array it would avoid confusion of accesing the values for example:
String line = "getInterfaceBounds-client.ry.test";
String test[] = line.split("[.]");
System.out.println(test[0]+test[1]+test[2]);

Related

How to split a string and get only segament after the question mark

how do you split a string and get the sentence only after the question mark. For example say you have the line : hello?myNameIs...
how could you only get what's after the question mark
many thanks
If all your use cases will be similar to the simple example you've stated, you could use a simple split.
The code:
String delim = "\\?";
String s = "hello?myNameIs";
String token[] = s.split(delim);
System.out.println(token[1]);
Gives the output:
myNameIs
Of course, you can tinker with it to solve your specific problems.
try this one
String sArray[] = src.split(Pattern.quote("?"));

The filter string - removing some chars

is there a function in Java which removed from a string unwanted chars given by me? If not, what the most effective way to do it. I would like realize it in JAVA
EDIT:
But, I want reach for example:
String toRescue="#8*"
String text = "ra#dada882da(*%"
and after call function:
string text2="#88*"
You can use a regular expression, for example:
String text = "ra#dada882da(*%";
String text2 = text.replaceAll("[^#8*]", "");
After executing the above snippet, text2 will contain the string "#88*".
The Java String has many methods which can help you, such as
String.replace(char old, char new);
String.split(regex);
String.substring(int beginIndex);
These and many others are described in the javadoc : http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

Split a String In Java against the split rule?

I have a string like this:
String str="\"myValue\".\"Folder\".\"FolderCentury\"";
Is it possible to split the above string by . but instead of getting three resulting strings only two like:
columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";
Or do I have to use an other java method to get it done?
Try this.
String s = "myValue.Folder.FolderCentury";
String[] a = s.split(java.util.regex.Pattern.quote("."));
Hi programmer/Yannish,
First of all the split(".") will not work and this will not return any result. I think java String split method not work for . delimiter, so please try java.util.regex.Pattern.quote(".") instead of split(".")
As I posted on the original Post (here), the next code:
String input = "myValue.Folder.FolderCentury";
String regex = "(?!(.+\\.))\\.";
String[] result=input.split(regex);
System.out.println("result: "+Arrays.toString(result));
Produces the required output (an array with two values):
result: [myValue.Folder, FolderCentury]
If the problem you're trying to solve is really that specific, you could do it even without using regular expression matches at all:
int lastDot = str.lastIndexOf(".");
columnArray[0] = str.substring(0, lastDot);
columnArray[1] = str.substring(lastDot + 1);

using regular expression as delimiter with StringTokenizer

I am new to java progrmming and came across the StringTokenizer class. The constructor accepts the string to be split and another optional delimiter string each character of which gets treated as an individual delimiter while splitting the original string. I was wondering if there is any way to split the string passing a regex as the delimiter. for example:
String s="34.5xy32.6y45.7x36xy"
StringTokenizer t=new StringTokenizer(s,"xy");
System.out.println(t.nextToken());
System.out.println(t.nextToken());
The actual output is:
34.5
32.6
However, the desired output is:
34.5
32.6y45.7x36
Hope you guys can help. Also, please suggest some way around if it is not possible with StringTokenizer class.
Thanks in advance.
p.s. Is there any way to know which character the StringTokenizer is currently using as delimiter out of the provided set?
Here you would want to use String.split(), this will give you an array with your desired output.
It will take your input and split it around exact matches of your string you provide. StringTokenizer will split around anyone of the set that you provide it rather than a regular expression.
So you change your code to:
String s="34.5xy32.6y45.7x36xy";
String[] splitString = s.split("xy");
System.out.println(splitString [0]);
System.out.println(splitString [1]);
For more complex examples you probably want boundary checking on the array also to make you don't go off the end of the array
Try with this.
String s="34.5xy32.6y45.7x36xy";
final String SPLIT_STR = "xy";
final String mainStr = "34.5xy32.6y45.7x36xy";
final String[] splitStr = mainStr.split(SPLIT_STR);
System.out.println("First Index Of xy : " +
mainStr.indexOf(SPLIT_STR));
for(int index=0; index < splitStr.length; index++) {
System.out.println("Split : " + splitStr[index]);
}

How to replace || (two pipes) from a string with | (one) pipe

I am getting response for some images in json format within this tag:
"xmlImageIds":"57948916||57948917||57948918||57948919||57948920||57948921||57948‌ ​922||57948923||57948924||57948925||57948926||5794892"
What i want to do is to separate each image id using .split("||") of the string class. Then append url with this image id and display it.
I have tried .replace("\"|\"|","\"|"); but its not working for me. Please help.
EDIT: Shabbir, I tried to update your question according to your comments below. Please edit it again, if I didn't get it right.
Use
.replace("||", "|");
| is no special char.
However, if you are using split() or replaceAll instead of replace(), beware that you need to escape the pipe symbol as \\|, because these methods take a regex as parameter.
For example:
public static void main(String[] args) {
String in = "\"xmlImageIds\":\"57948916||57948917||57948918||57948919||57948920||57948921||57948‌922||57948923||57948924||57948925||57948926||5794892\"".replace("||", "|");
String[] q = in.split("\"");
String[] ids = q[3].split("\\|");
for (String id : ids) {
System.out.println("http://test/" + id);
}
}
I think I know what your problem is. You need to assign the result of replace(), not just call it.
String s = "foo||bar||baz";
s = s.replace("||", "|");
System.out.println(s);
I tested it, and just calling s.replace("||", "|"); doesn't seem to modify the string; you have to assign that result back to s.
Edit: The Java 6 spec says "Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar." (the emphasis is mine).
According to http://docs.oracle.com/javase/6/docs/api/java/lang/String.html, replace() takes chars instead of Strings. Perhaps you should try replaceAll(String, String) instead? Either that, or try changing your String ("") quotation marks into char ('') quotation marks.
Edit: I just noticed the overload for replace() that takes a CharSequence. I'd still give replaceAll() a try though.
String pipe="pipes||";
System.out.println("Old Pipe:::"+pipe);
System.out.println("Updated Pipe:::"+pipe.replace("||", "|"));
i dont remember how it works that method... but you can make your own:
String withTwoPipes = "helloTwo||pipes";
for(int i=0; i<withTwoPipes.lenght;i++){
char a = withTwoPipes.charAt(i);
if(a=='|' && i<withTwoPipes.lenght+1){
char b = withTwoPipes.charAt(i+1);
if(b=='|' && i<withTwoPipes.lenght){
withTwoPipes.charAt(i)='';
withTwoPipes.charAt(i+1)='|';
}
}
}
I think that some code like this should work... its not a perfect answer but can help...

Categories

Resources