How to split a string and get a specific string in android? - android

I want to split a string and get a word finally. My data in database is as follows.
Mohandas Karamchand Gandhi (1869-1948), also known as Mahatma Gandhi, was born in Porbandar in the present day state of Gujarat in India on October 2, 1869.
He was raised in a very conservative family that had affiliations with the ruling family of Kathiawad. He was educated in law at University College, London.
src="/Leaders/gandhi.png"
From the above paragraph I want get the image name "gandhi". I am getting the index of "src=". But now how can I get the image name i.e "gandhi" finally.
My Code:
int index1;
public static String htmldata = "src=";
if(paragraph.contains("src="))
{
index1 = paragraph.indexOf(htmldata);
System.out.println("index1 val"+index1);
}
else
System.out.println("not found");

You can use the StringTokenizer class (from java.util package ):
StringTokenizer tokens = new StringTokenizer(CurrentString, ":");
String first = tokens.nextToken();// this will contain one word
String second = tokens.nextToken();// this will contain rhe other words
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method

Try this code. Check if it working for you..
public String getString(String input)
{
Pattern pt = Pattern.compile("src=.*/(.*)\\..*");
Matcher mt = pt.matcher(input);
if(mt.find())
{
return mt.group(1);
}
return null;
}
Update:
Change for multiple item -
public ArrayList<String> getString(String input)
{
ArrayList<String> ret = new ArrayList<String>();
Pattern pt = Pattern.compile("src=.*/(.*)\\..*");
Matcher mt = pt.matcher(input);
while(mt.find())
{
ret.add(mt.group(1));
}
return ret;
}
Now you'll get an arraylist with all the name. If there is no name then you'll get an empty arraylist (size 0). Always make a check for size.

Related

Sort ArrayList by search keyword

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

Android : replacing characters in a string

In my phonebook on my mobile I have all sorts of contacts like :
+(353) 085 123 45 67
00661234567
0871234567
(045)123456
I'm putting them all into E.164 format which I've largely completed but the question I need resolved is this:
How can I strip all characters (including spaces) except numbers in my string, apart from the first character if it is '+' or a number ?
string phoneNumberofContact;
So for example the cases above would look like :
+3530851234567
00661234567
0871234567
045123456
Update
To handle + only in the first position, you could do:
boolean starsWithPlus = input.charAt(0) == '+';
String sanitized = input.replaceAll("[^0-9]", "");
if (startsWithPlus) {
sanitized = "+" + sanitized;
}
So basically I'm checking to see if it starts with plus, then stripping out everything but digits, and then re-adding the plus if it was there.
Original
Assuming you only want to keep + or digits, a simple regex will work, and String provides the replaceAll() method to make it even easier.
String sanitized = input.replaceAll("[^+0-9]", "");
This method would do the trick
public String cleanPhoneDigits(String phonenum) {
StringBuilder builder = new StringBuilder();
if (phonenum.charAt(0).equals('+') {
builder.append('+');
}
for (int i = 1; i < phonenum.length(); i++) {
char c = phonenum.charAt(i);
if (Character.isDigit(c)) {
builder.append(c);
}
}
return builder.toString();
}

How to get specific word in a whole string?

I am creating and android app that randomly generates any category, I would like to get the given random category word. This is the example string
String="The category Animals that starts with a letter J";
or
String="The category Colors that starts with a letter V";
I need to get the word Animals or Colors every random String is generated
A not so advanced solution, but easy to understand:
public void findCategory() {
String string = "The category Colors that starts with a letter V";
String[] split = string.split(" ");
int i;
for (i = 0; i < split.length; i++) {
if ("category".equals(split[i])) {
break;
}
}
System.out.println(split[i + 1]);
}
You may use regex.
Matcher m = Pattern.compile("\\bcategory\\s+(\\S+)").matcher(str);
while(m.find()) {
System.out.println(m.group(1));
}
OR
Matcher m = Pattern.compile("(?<=\\bcategory\\s)\\S+").matcher(str);
while(m.find()) {
System.out.println(m.group());
}
Please use Matcher and Pattern -
String input = "The category Animals that starts with a letter J";
Matcher m1 = Pattern.compile("^The category (.*) that starts with a letter (.*)$").matcher(input);
if(m1.find()) {
String _thirdWord = m1.group(1); // Animals
String _lastWord = m1.group(2); // J
System.out.println("Third word : "+_thirdWord);
System.out.println("Last Word : "+_lastWord);
}
Use this, it might fix your issue
String string = "The category Colors that starts with a letter V";
String[] ar = string.split(" ");
System.out.println(ar[2]);

ReplaceAll not working

I'm using google volley to retrieve source code from website. Some looping was done to capture the value in the code. I've successfully captured the data I wanted, but error was shown: NumberFormatException: Invalid float: "2,459.00"
My intention was to store the value after the class=ListPrice>
Sample:
RM 2,899.00
The example value of the source code I wanted to save is "RM2,459.00 "
Below is the code I've written:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lazada_result);
lelongResult = (TextView) findViewById(R.id.lelong_result);
RequestQueue lelong = MyVolley.getRequestQueue(this);
StringRequest myLel = new StringRequest(
Method.GET,
"http://list.lelong.com.my/Auc/List/List.asp?DA=A&TheKeyword=iphone&x=0&y=0&CategoryID=&PriceLBound=&PriceUBound=",
RetrieveLelong(), createMyReqErrorListener());
lelong.add(myLel);
}
private Response.Listener<String> RetrieveLelong() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ArrayList<Float> integers = new ArrayList<>();
String to = "class=ListPrice>";
String remainingText = response;
String showP = "";
while (remainingText.indexOf(to) >= 0) {
String tokenString = remainingText.substring(remainingText
.indexOf(to) + to.length());
String priceString = tokenString.substring(0,
tokenString.indexOf("<"));
float price = Float.parseFloat(priceString.replaceAll("[^\\d,]+", "").trim());
integers.add((price / 100));
remainingText = tokenString;
}
for (int i = 0; i < integers.size(); i++) {
String test1 = Float.toString(integers.get(i));
showP += test1 + "\n";
}
lelongResult.setText(showP);
}
};
}
The problem was as below:
I've tried all sort of replaceAll(),
1)replaceAll("[^\d,]+","") result:2,89900
replace all character except digits and comma works.
2)replaceAll("[^\d]+","") result:Invalid int""
replace all character include comma and dot ,not working
3)replaceAll("[^\d.]+,"") result:Invalid int""
replace all character exclude digits and dot, not working
From the experiment 2&3 coding above,I've noticed that if the comma were removed,i cant parseFloat as the value received by it is: "".NumberFormatException:Invalid Float:"" shown.
From the experiment 1,NumberFormatException:Invalid Float "2,45900" is showned.
The problem was replacing comma ,the code will not work but with the presence of comma ,the value cannot be stored into string
try this:
float price = Float.parseFloat(priceString.replaceAll("RM", "").trim());
use `replaceAll(Pattern.quote(","), "");
EDIT
if you want only numbers then use this
String s1= s.replaceAll("\D+","");
Try to parse the number by specifying the Locale.
NumberFormat format = NumberFormat.getInstance(Locale.KOREAN);
Number number = format.parse(priceString.replaceAll("RM", ""));
double d = number.doubleValue();
I'm just guessing the locale, don't know what you should use, depends on country
You need to do it one by one
priceString=priceString.replaceAll("\\D", "");
priceString=priceString.replaceAll("\\s", "");
now
priceString=priceString.trim();
float price = Float.parseFloat(priceString);
the problem is that in your code:
priceString.replaceAll(Pattern.quote(","), "");
float price = Float.parseFloat(priceString.replaceAll("\\D+\\s+", "").trim());
You are replacing coma but not storing the value!
you have to do:
priceString = priceString.replaceAll(",", "");
float price = Float.parseFloat(priceString.replaceAll("\\D+\\s+", "").trim());
I'm not sure of the pattern "\D+\s" because if you remove the coma you don't need to replace anything else (except "RM" that i assume you already removed)
Update: set locale and parse a number:
NumberFormat format = NumberFormat.getInstance(Locale.KOREAN);
Number number = format.parse(priceString.replaceAll("RM", ""));
double d = number.doubleValue();

How to split this String?

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

Categories

Resources