Split a String In Java against the split rule? - java

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);

Related

Getting rid of half a String in Android

Need help with getting rid of half of a string in android studio. The string is:
final String strOrigin = String.valueOf(origin).trim();
The value that is returned is;
"Point{type=Point, bbox=null, coordinates=[27.993726079654873,-26.14686805145815]}"
I want to be left with only the numbers of that, in the String. I have tried;
strOrigin.replace("Point{type=Point, bbox=null, coordinates=", "");
But it isn't working. Any help would be appreciated.
In Java strings are immutable. You must assign the result to a new string:
String strResult = strOrigin.replace("Point{type=Point, bbox=null, coordinates=", "");
Make your life simpler by just getting the coordinates:
final String strOigin = origin.coordinates().stream()
.map(String::valueOf)
.collect(Collectors.joining(",","{","}"));
Or, if you're stuck on java 7:
final String strOigin = String.format(
"{%s,%s}",
String.valueOf(origin.latitude()),
String.valueOf(origin.longitude())
);
Maybe you forgot that replace() returns the result and you must assign it to a string:
String strOrigin = "Point{type=Point, bbox=null, coordinates=[27.993726079654873,-26.14686805145815]}";
String str = strOrigin
.replace("Point{type=Point, bbox=null, coordinates=", "")
.replace("}","");
System.out.println(str);
will print:
[27.993726079654873,-26.14686805145815]
This should do the trick
String s="blabla coordinates=[27.993726079654873,-26.14686805145815] ";
String requiredString = s.substring(s.indexOf("[") + 1, s.indexOf("]"));
will print:
27.993726079654873,-26.14686805145815
Than you can cast it to double or latlong format
Have a look at regular expressions, they allow you to define more flexible search patterns. In your example you only find the coordinates if the rest of the string matches the pattern exactly, but if you happen to get some other value of bbox, or even extra space it will not work. This will always match everything between a pair of square brackets:
String c = origin.replaceAll(".+?(\\[.+?\\]).+?", "$1");
http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

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

Can a string be converted to a string containing escape sequences in Java?

Say I enter a string:-
Hello
Java!
I want the output as:-
Hello\nJava!
Is there any way in which I could get the output in this format?
I am stuck on this one and not able to think about any logic which could do this for me.
It looks like http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html does what you want.
EG
String escaped = StringEscapeUtils.escapeJava(String str)
Will return "Hello\nJava!" when supplied with your string.
Hm..You can replace the new line character(\n) with \\n. For example:
String helloWithNewLine = "Hello\nJava";
String helloWithoutNewLine = helloWithNewLine.replace("\n", "\\n");
System.out.println(helloWithoutNewLine);
Output:
Hello\nJava

Error when splitting a string

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]);

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