what is the best way to extract a substring from a string in android?
If you know the Start and End index, you can use
String substr=mysourcestring.substring(startIndex,endIndex);
If you want to get substring from specific index till end you can use :
String substr=mysourcestring.substring(startIndex);
If you want to get substring from specific character till end you can use :
String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue"));
If you want to get substring from after a specific character, add that number to .indexOf(char):
String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue") + 1);
substring():
str.substring(startIndex, endIndex);
Here is a real world example:
String hallostring = "hallo";
String asubstring = hallostring.substring(0, 1);
In the example asubstring would return: h
There is another way , if you want to get sub string before and after a character
String s ="123dance456";
String[] split = s.split("dance");
String firstSubString = split[0];
String secondSubString = split[1];
check this post-
how to find before and after sub-string in a string
substring(int startIndex, int endIndex)
If you don't specify endIndex, the method will return all the
characters from startIndex.
startIndex : starting index is inclusive
endIndex : ending index is exclusive
Example:
String str = "abcdefgh"
str.substring(0, 4) => abcd
str.substring(4, 6) => ef
str.substring(6) => gh
you can use this code
public static String getSubString(String mainString, String lastString, String startString) {
String endString = "";
int endIndex = mainString.indexOf(lastString);
int startIndex = mainString.indexOf(startString);
Log.d("message", "" + mainString.substring(startIndex, endIndex));
endString = mainString.substring(startIndex, endIndex);
return endString;
}
in this mainString is a Super string.like
"I_AmANDROID.Devloper"
and lastString is a string like"." and startString is like"_".
so this function returns "AmANDROID".
enjoy your code time.:)
use text untold class from android: TextUtils.substring (charsequence source, int start, int end)
You can use subSequence , it's same as substr in C
Str.subSequence(int Start , int End)
When finding multiple occurrences of a substring matching a pattern
String input_string = "foo/adsfasdf/adf/bar/erqwer/";
String regex = "(foo/|bar/)"; // Matches 'foo/' and 'bar/'
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input_string);
while(matcher.find()) {
String str_matched = input_string.substring(matcher.start(), matcher.end());
// Do something with a match found
}
The best way to get substring in Android is using (as #user2503849 said) TextUtlis.substring(CharSequence, int, int) method. I can explain why. If you will take a look at the String.substring(int, int) method from android.jar (newest API 22), you will see:
public String substring(int start) {
if (start == 0) {
return this;
}
if (start >= 0 && start <= count) {
return new String(offset + start, count - start, value);
}
throw indexAndLength(start);
}
Ok, than... How do you think the private constructor String(int, int, char[]) looks like?
String(int offset, int charCount, char[] chars) {
this.value = chars;
this.offset = offset;
this.count = charCount;
}
As we can see it keeps reference to the "old" value char[] array. So, the GC can not free it.
In the newest Java it was fixed:
String(int offset, int charCount, char[] chars) {
this.value = Arrays.copyOfRange(chars, offset, offset + charCount);
this.offset = offset;
this.count = charCount;
}
Arrays.copyOfRange(...) uses native array copying inside.
That's it :)
Best regards!
All of The responders gave good answers. However, I am giving you all relatable methods for this so that any one can get from one place, I'll edit my answer if I find something new.
substring(0)- use for cut string from given specific char.
Substring(0,2)- give you sub string from starting(0) and ending(2) characters.
Split("NAME")- return you string in two parts first is that you use in split "NAME" and another part is rest of string combine.
subSequence(0,3) - returns sequence of give start(0) and ending index(3).
This one is not specifically use for split string but though it may be use full for some one
startswith("A",3)- returns string for specific starting character.
For example:
String s = "StackOverflow";
String[] split = s.split("Stack");
System.out.println("STRING NAME:"+s.substring(2));
System.out.println("STRING NAME:"+s.substring(2,3));
System.out.println("STRING NAME:"+split[1]);
System.out.println("STRING NAME:"+split[0]);
System.out.println("STRING NAME:"+s.subSequence(2,5));
Output:
1)ackOverflow
2)a
3)Overflow
4)stack
5)ack
I hope this will give you enough information that you require.
Related
I have an ArrayList with This values
"Babel"
"Isabelle"
"Elon"
"Eloise"
I'm typing "el" on the search, I sort the list and I would like to have this result
"Eloise"
"Elon"
"Babel"
"Isabelle"
Because "Eloise" start with my search "el" like "Elon" and then "Babel" because alphabetically is before "Isabelle"
I don't know how to sort by the firsts chars of the array I try to substring names
users.sort((o1, o2) -> {
String name1 = o1.getNickname();
String name2 = o2.getNickname();
if (o1.getNickname().length() >= finalS.length()) {
name1 = o1.getNickname().substring(0, finalS.length());
}
if (o2.getNickname().length() >= finalS.length()) {
name2 = o2.getNickname().substring(0, finalS.length());
}
return name1.compareTo(name2);
});
But this return name1.compareTo(name2); compare the cutted String and order alphabetical.
I try to add this below the substring
if (name1.contains(finalS)) return 1;
or
if (name2.contains(finalS)) return 1;
nothing work Babel is always at the first position
In most cases, the factory methods in the Comparator interface are suitable and allow to reduce the redundancy of applying operations to both arguments of the comparator.
Since your input is "el" but the names start with an uppercase letter, you want a case insensitive partial matching, followed by sorting by the strings’ natural order.
List<String> users = Arrays.asList("Babel", "Isabelle", "Elon", "Eloise");
String finalS = "el";
users.sort(Comparator.comparing(
(String u) -> !finalS.regionMatches(true, 0, u, 0, finalS.length()))
.thenComparing(Comparator.naturalOrder()));
users.forEach(System.out::println);
Eloise
Elon
Babel
Isabelle
Since apparently there’s a class User whose Nickname property you want to compare, the complete sorting code would look like
users.sort(Comparator.comparing(User::getNickname, Comparator.comparing(
(String u) -> !finalS.regionMatches(true, 0, u, 0, finalS.length()))
.thenComparing(Comparator.naturalOrder())));
Your Comparator should look kind of like this:
Sorts those which start with your search first, then those which only contain them. But the best way for searching would be to use diff-match-patch (https://github.com/google/diff-match-patch).
public int compare(User o1, User o2) {
String search = YOUR_SEARCH.toLowerCase();
String name1 = o1.getNickname().toLowerCase();
String name2 = o2.getNickname().toLowerCase();
int i = Boolean.compare(name2.startsWith(search), name1.startsWith(search));
if (i != 0)
return i;
i = Boolean.compare(name2.contains(search), name1.contains(search));
if (i != 0)
return i;
return name2.compareTo(name1);
}
I have string in forloop, I want add that in to another string like the given format
for (int i = 0; i < profiles.length(); i++) {
JSONObject c = profiles.getJSONObject(i);
String admnno = c.getString(TAG_ADMNNO);
}
The result should be like this
"Rajesh", "Mahesh", "Vijayakumar"
or
final CharSequence[] items = {"Rajesh", "Mahesh", "Vijayakumar"};
The adminno should be in double quotes and following comma. Its in android doin Background()
Use \" for this
For example String str="\"Rajesh\""
Try this,
if (TextUtils.isEmpty(string))
return "";
final int lastPos = string.length() - 1;
if (lastPos < 0 || (string.charAt(0) == '"' && string.charAt(lastPos) == '"'))
return string;
return "\"" + string + "\"";
Another option is to use Kotlin's multiline strings. Especially useful when you need hardcode big JSON for UTests:
val jsonString = """
{
"string_key": "value",
"boolean_key": true
}
"""
You can also try this
var id = "\"id\": \""
Output = "id": "
You have to escape the quote using \" like below:
public static String getQuotedString(String sample){
return "\"".concat(sample).concat("\"");
}
In Kotlin, you can use a variable value like this way
val searchText = "Android"
textview.text = "5 articles found for \"$searchText\""
For fixed string:
String str="5 articles found for \"IOS\" "
value is equal for
5 articles found for "IOS"
I have a String separated by commas as follows
1,2,4,6,8,11,14,15,16,17,18
This string is generated upon user input. Suppose the user wants to remove any of the numbers, I have to rebuild the string without the specified number.
If the current string is:
1,2,4,6,8,11,14,15,16,17,18
User intents to remove 1, the final string has to be:
2,4,6,8,11,14,15,16,17,18
I tried to achieve this using the following code:
//String num will be the number to be removed
old = tv.getText().toString(); //old string
newString = old.replace(num+",",""); //will be the new string
This might be working sometimes but it is sure that it won't work for the above example I have shown, if I try to remove the 1, it also removes the last part of 11, because there also exists 1.
well you can use this. Its the most simplest approach i can think of:
//String num will be the number to be removed
old=","+tv.getText().toString()+",";//old string commas added to remove trailing entries
newString=old.replace(","+num+",",",");// will be the new string
newString=newString.substring(1,newString.length()-1); // removing the extra commas added
This would work for what you want to do. I have added a comma at the start and end of your string so that you can also remove the first and last entries too.
You can split the string first and check for the number where you append those value that is not equivalent to the number that will get deleted;
sample:
String formated = "1,2,4,6,8,11,14,15,16,17,18";
String []s = formated.split(",");
StringBuilder newS = new StringBuilder();
for(String s2 : s)
{
if(!s2.equals("1"))
newS.append(s2 + ",");
}
if(newS.length() >= 1)
newS.deleteCharAt(newS.length() - 1);
System.out.println(newS);
result:
2,4,6,8,11,14,15,16,17,18
static public String removeItemFromCommaDelimitedString(String str, String item)
{
StringBuilder builder = new StringBuilder();
int count = 0;
String [] splits = str.split(",");
for (String s : splits)
{
if (item.equals(s) == false)
{
if (count != 0)
{
builder.append(',');
}
builder.append(s);
count++;
}
}
return builder.toString();
}
String old = "1,2,4,6,8,11,14,15,16,17,18";
int num = 11;
String toRemove = "," + num + "," ;
String oldString = "," + old + ",";
int index = oldString.indexOf(toRemove);
System.out.println(index);
String newString = null;
if(index > old.length() - toRemove.length() + 1){
newString = old.substring(0, index - 1);
}else{
newString = old.substring(0, index) + old.substring(index + toRemove.length() -1 , old.length());
}
System.out.println(newString);
I currently have the code below and it successfully returns all the numbers that are present in a string I have.
An example of the string would be say: 1 egg, 2 rashers of bacon, 3 potatoes.
Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(o1.getIngredients());
while (matcher.find()) {
Toast.makeText(this, "" + matcher.group(), Toast.LENGTH_LONG).show();
}
However, I would like to multiply these numbers by say four and then place them back in the original string. How can I achieve this?
Thanks in advance!
I've never tried this, but I think appendReplacement should solve your problem
Doing arithmetic is a little complicated while doing the find()
Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(test);
int start = 0;
int end = 0;
StringBuffer resultString = new StringBuffer();
while (matcher.find()) {
start = matcher.start();
// Copy the string from the previous end to the start of this match
resultString.append(test.substring(end, start));
// Append the desired new value
resultString.append(4 * Integer.parseInt(matcher.group()));
end = matcher.end();
}
// Copy the string from the last match to the end of the string
resultString.append(test.substring(end));
This StringBuffer will hold the result you are expecting.
I want to split this string
String info = "0.542008835 meters height from ground";
from this i want to get only two decimals like this 0.54.
by using this i am getting that
String[] _new = rhs.split("(?<=\\G....)");
But i am facing problem here, if string does't contain any decimals like this string
String info = "1 meters height from ground";
for this string i am getting those characters upto first 4 in the split string like 1 me.
i want only numbers to split if it has decimals, How to solve this problem.
if(info.contains("."))
{
String[] _new = rhs.split("(?<=\\G....)");
}
I think you can check by white space after first value. see this
If you get the space then get first character only.
For checking if a string contains whitespace use a Matcher and call it's find method.
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
If you want to check if it only consists of whitespace then you can use String.matches:
boolean isWhitespace = s.matches("^\\s*$");
You could use a regex to do this as an alternative to Deepzz's method, this will handle the case where there is a '.' in the later part of the String, I've included an example below. It's not clear from your question is you actually want to remaining part of the String, but you could add a second group to the reg ex to capture this.
public static void main(String[] args) {
final String test1 = "1.23 foo";
final String test2 = "1 foo";
final String test3 = "1.234 foo";
final String test4 = "1.234 fo.o";
final String test5 = "1 fo.o";
getStartingDecimal(test1);
getStartingDecimal(test2);
getStartingDecimal(test3);
getStartingDecimal(test4);
getStartingDecimal(test5);
}
private static void getStartingDecimal(final String s) {
System.out.print(s + " : ");
Pattern pattern = Pattern.compile("^(\\d+\\.\\d\\d)");
Matcher matcher = pattern.matcher(s);
if(matcher.find()) {
System.out.println(matcher.group(1));
} else {
System.out.println("Doesn't start with decimal");
}
}
Assuming the number is always the first part of the string:
String numStr = rhs.split(" ")[0];
Double num = Double.parseDouble(numStr);
After that you can use the String Formatter to get the desired representation of the number.
This will work when you know the String near the numbers, with int and double numbers as well.
String a ="0.542008835 meters height from ground";
String b = a.replace(" meters height from ground", "");
int c = (int) ((Double.parseDouble(b))*100);
double d = ((double)c/100);