Getting rid of half a String in Android - java

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

Related

Removing the last character from a string

I am having trouble with a recent Java project. I am attempting to just the String "white" from the String. No matter what method I attempt, the last "_" always remains.
String questionText = "The white house is _white_";
String correctResponse = questionText.replace(questionText.substring(0, questionText.indexOf("_")+1), "");
correctResponse.substring(0,correctResponse.length()-1);
System.out.println(correctResponse);
substring don't modify original object.
use
correctResponse = correctResponse.substring(0, correctResponse.length() - 1);
I would use a regular expression to group everything between underscores, and then String.replaceAll(String, String) to actually remove everything but the group. Like,
String correctResponse = questionText.replaceAll(".+\\s+_(.+)_", "$1"); // white
If the string you want is always between underscores (or at least after one underscore), you could just split the string and take the substring at index 1:
String correctResponse = questionText.split("_")[1];
Use lastIndexOf
String correctResponse = questionText.replace(questionText.substring(questionText.indexOf("_"), questionText.lastIndexOf("_")+1), "");
You think to complicated - why do you need replace? You can achieve the same with substring
First statement
String correctResponse = questionText.substring(questionText.indexOf("_")+1)
// ==> correctResponse = "white_"
Second statement
correctResponse = correctResponse.substring(0, correctResponse.indexOf("_"))
// ==> correctResponse = "white"
As #neuo pointed out, substring won't change the string..
You just need to change line 3.
Original Line :
correctResponse.substring(0,correctResponse.length()-1);
Correct Line :
correctResponse = correctResponse.substring(0,correctResponse.length()-1);
If you use a regular expression you don't have to check index bounaries.
String string = "Merry Christmas!".replaceAll(".$", "");
System.out.println(string);
will print out
Merry Christmas

Java Parsing outputted message

I need to parse this into strings in the most efficient way. I currently have this line
D[date-string] T[time-string] N[name-string] M[message-string]
Needs to be parsed into four strings respectively,
private String time; //would equal time-string
private String date; //would equal date-string
private String name; //would equal name-string
private String message; //would equal message-string
Is there an easy way to do this?
You can use regex and groups to match and extract that kind of data:
For example, something like:
Pattern p = Pattern.compile("D(\\w+) T(\\w+) N(\\w+) M(\\w+)");
Matcher m = p.matcher(yourString);
if (m.matches()){
String d = m.group(1);
String t = m.group(2);
String n = m.group(3);
String w = m.group(4);
}
The patterns within the parentheses are saved into groups, which you can extract after the match (it starts with 1, since 0 is the whole match).
You have then to change that to the characters and patterns you want to accept.
I'm not sure if I've understood you but looks like using regular expression is the easiest way to do this kind of parsing.
The below logic will work. How regix will hep not sure. But the below code will also be ok as it is not looping and anything so i think it will could be the optimum solution.
String s = "D[date-string] T[time-string] N[name-string] M[message-string]";
String[] str = s.split(" ");
String date = str[0].substring(str[0].indexOf("[")+1, str[0].lastIndexOf("]")); //would equal time-string
String time=str[1].substring(str[1].indexOf("[")+1, str[1].lastIndexOf("]")); //would equal date-string
String name=str[2].substring(str[2].indexOf("[")+1, str[2].lastIndexOf("]")); //would equal name-string
String message=str[3].substring(str[3].indexOf("[")+1, str[3].lastIndexOf("]"));
Wow, easy easy easy!
D[(.*?)] for the date!
https://regex101.com/r/vM0yW8/1
Take a look here and here, you will have to tune it accordingly.

Java check and parse out string containing character sequence

I need to dynamically check for presence of char sequence "(Self)" in a string and parse it out.
So if my string say myString is
"ABCDEF (Self)"
it should return myString as
"ABCDEF"
What is the best way of doing it? Can it be done in a single step?
You may use the replace function as follows:
myString = myString.replace(" (Self)","");
Here, read more about things to note with String.replace or the function definition itself. Note that it is overloaded with a char variant, so you can do two kinds of things with a similar function call.
You may use the replaceAll method from the String class as follows:
myString = myString.replaceAll(Pattern.quote("(Self)"), ""));
Try following:
String test="ABCDEF (Self)";
test=test.replaceAll("\\(Self\\)", "");
System.out.println(test.trim());
Output :
ABCDEF
The dig is to use Regular Expressions for more on it visit this link.
And the code won't have a problem if there is no Self in string.
Just check out the String class' public methods.
String modifyString(String str) {
if(str.contains("(Self)")) {
str = str.replace("(Self)", "");
str = str.trim();
}
return str;
}
From the question, I understand that from source string ABCDEF (Self) also the space between F and ( should be removed.
I would recommend to use regEx if you are comfortable with it, else:
String OrigString = "ABCDEF (Self)";
String newString= OrigString.replaceAll("\\(Self\\)", "").trim();
System.out.println("New String : --" +newString+"--");
The Regular Expression for your case would be:
\s*\(Self\)\s*
Tested Java Code using regular expression would be:
String newRegExpString = OrigString.replaceAll("\\s*\\(Self\\)\\s*", "");
System.out.println("New String : -" +newRegExpString+"--");
Output:
New String : --ABCDEF--
New String : -ABCDEF--

Getting the last part of the string

I have a string :
"id=40114662&mode=Edit&reminderId=44195234"
All i want from this string is the final number 44195234. I can't use :
String reminderIdFin = reminderId.substring(reminderId.lastIndexOf("reminderId=")+1);
as i cant have the = sign as the point it splits the string. Is there any other way ?
Try String.split(),
reminderIdFin.split("=")[3];
You can use indexOf() method to get where this part starts:
int index = reminderIdFin.indexOf("Id=") + 3;
the plus 3 will make it so that it jumps over these characters. Then you can use substring to pull out your wanted string:
String newString = reminderIdFin.substring(index);
Remove everything else and you'll be left with your target content:
String reminderIdFin = reminderId.replaceAll(".*=", "");
The regex matches everything up to the last = (the .* is "greedy").

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

Categories

Resources