I have the String content://com.android.contact/data/5032 in a variable Str1. I want to manipulate Str1 so that I will get 5032 in another string variable.
Can anyone suggest the answer?
String str1 = "content://com.android.contact/data/5032"
String val = str1.substring(str1.lastIndexOf("//")+1);
If you want go get digits from the given string try this:
String str = "content://com.android.contact/data/5032";
String str2 = str.replaceAll("\\D+","");
System.out.println(str2);
Output:
5032
If you want to split try this:
String[] string = str.split("//|/");
System.out.println(string[string.length -1 ]);
Output:
5032
String str1 = "content://com.android.contact/data/5032";
String str2 = str1.substring(str1.lastIndexOf("/")+1, str1.length());
if you only want the last 4 chars, you can do something like this
String s = "this is a string";
String ss = s.substring(s.length()-4, s.length());
but if you need to extract the number from random positions, you will have to use regular expressions.
Please write names of variables starting with a small letter. You can use the split method to do this. You might find this related question interesting: How to split a string in Java.
Related
String str1 = "The rumour is that the neighbours displayed good behaviour by labouring to help Mike because he is favoured.";
str1.replaceAll("our", "or");
System.out.println(str1);
Method replaceAll returns a new string where each occurrence of the matching substring is replaced with the replacement string.
Your code doesn't work because String is immutable. So, str1.replaceAll("our", "or"); doesn't change str1.
Try this code:
String str1 = "I am trying to replace the pattern.";
String str2 = str1.replaceAll("replace", "change");
System.out.println(str2);
If you don't what str2, try this code:
String str1 = "I am trying to replace the pattern.";
System.out.println(str1.replaceAll("replace", "change"));
And read about Immutability of Strings in 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
I have a string as follows:
"[error=<null>,EntityID=105378032, Context=<null>]"
and i want to extract the EntityID( in this case 105378032), but i want a generalize solution of doing it.
What is the most efficient way of doing it.
I don't want to traverse the string and get that part.
Did you try regex like .*EntityID=(.*?),.* which mean get the group of characters between EntityID= and the next comma , using replaceAll :
String str = "[error=,EntityID=105378032, Context=]";
System.out.println(str.replaceAll(".*EntityID=(.*?),.*", "$1"));// output 105378032
regex demo
Using Regular expressions seems to be the best way out.
This code works:
String str = "[error=,EntityID=105378032, Context=]";
String[] arr = str.split("EntityID="); //splits it on the part "EntityID="
String[] arr1 = arr[1].split(","); // splits it on the next comma in the 'right' half of your string.
System.out.println(arr1[0]); //prints the 'left' half before the comma.
Ideone link here.
Hope this helps!
You can use this method it's work like a charm
public static String getSubString(String mainString, String lastString, String startString) {
String endString = "";
int endIndex = mainString.indexOf(lastString);
int startIndex = mainString.indexOf(startString);
endString = mainString.substring(startIndex, endIndex);
return endString;
}
Result:
String resultStr = getSubString(yourFullString,",Context","EntityID=");
Happy codding.
This is an interview question. I was thinking of a solution in java. This questions seems very simple, is there a catch here?
I was thinking of the following solution:
string1 + 1*hash(String1) + string2 + 2*hash(String2).
If I concat strings like this, then I can decode them as well easily into 2 separate strings.
Am I missing something in the question?
Encode:
String encoded = new JsonArray().add(str1).add(str2).toString();
Decode:
JsonArray arr = JsonArray.readFrom(encoded);
String str1 = arr.get(0).asString();
String str2 = arr.get(1).asString();
Here I use minimal-json lib, but it's pretty similar with any other JSON library as well.
Note that it's usually a bad idea to invent new formats of encoding the information into the string as you have plenty of existing ones (xml, json, yaml, etc.) which already solved all the possible issues like symbol escaping and exception handling.
To encode:
String encoded = ""+str1.length()+"/"+str1+str2;
To decode:
String[] temp = encoded.split("/", 2);
int length1 = Integer.parseInt(temp[0]);
String str1 = temp[1].substring(0, length1);
String str2 = temp[1].substring(length1);
Explanation:
The encoded string is in the form "<number>/<str1><str2>". When you call split(regex, limit) the size of the resulting array will be at most limit, considering only the first matches of regex. Thus even if your strings contain the character / you can be sure that the resulting array will be {"<number>", "<str1><str2>"}.
the substring(begin, end) return a string starting at begin inclusive and ending at end exclusive, giving you a resulting substring of end-begin length. Since you are calling it with values(0, str1.length()) what you get is exactly str1. The last call will return a substring from str1.length(), which is also the index of the first character of str2, to the end of the string (which is the end of str2).
Reference: String javadoc page
One way is to use the length of the first string.
// encode
String concat = string1 + string2;
// decode
String str1 = concat.substring( 0, string1.length() );
String str2 = concat.substring( string1.length(), concat.length() );
Another way is to use a delimiter. But the delimiter character should not be included in any of the strings to be joined.
// encode
String concat = "hello" + "`" + "world!";
// decode
String[] decoded = concat.split("`");
String str1 = decoded[0];
String str2 = decoded[1];
I have a string "content/users/user/missions/mission" .I need to get "content/users/user/missions" from it [i.e. string upto the last delimiter] .How to proceed ?
If your requirement is that simple then you could do the following:
String string = "content/users/user/missions/mission";
String newString = string.substring(0, string.lastIndexOf('/'));
There are more fancy ways of doing this, regex could be one.
Use lastIndexOf and substring methods from String class.
String str = "content/users/user/missions/mission";
String result = str.substring(0,str.lastIndexOf('/'));