How to get specific word in a whole string? - android

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

Related

how to get the indexes of all the occurences of words in string?

I want to get indexes of all the occurences of string_to_be_search
Input:
String line="hello this is prajakta , how are you?? hello this is prajakta!"
String text_to_search= "hello this is prajakta"
Here the occurrences of text_to_search is 2 so I need list of starting indexes
Output:
List l=[0,39]
Also I have tried a code below
public List getIndexesOfMultipleOccuredString(String originalString,String textToSearch) {
int i, last = 0, count = 0;
List l = new ArrayList();
do {
i = originalString.indexOf(textToSearch, last);
if (i != -1) l.add(i);
last = i + textToSearch.length();
} while (i != -1);
return l;
}
BUT
if my input is as follows
String line="hello this is prajakta ,i love to drive car and i am a carpainter"
String text_to_search="car"
Output:
It gives me two indexes as carpainter contains car which i don't want
Output should be [39]
This is how you do it using regex(word matching)
String line= "hello this is prajakta , how are you?? hello this is prajakta!";
String text_to_search = "\\bhello this is prajakta\\b";
ArrayList<Integer> list = new ArrayList<>();
Pattern p = Pattern.compile(text_to_search);
Matcher m = p.matcher(line);
while (m.find()) {
list.add(m.start());
}
Log.i("All occurrences", "values are " + list.toString());
Output: [0, 39]
If you search using these strings
String line="hello this is prajakta ,i love to drive car and i am a carpainter";
String text_to_search="car";// use as "\\bcar\\b"
Output [40]

Compare 2 textbox values charcter by character

I want to comapare two textbox values words by words and check if the words are same or not. If its not same then it should tell me the percentage of matching words.
For example : I am a good boy(text box1)
Am a god boy (text box 2)
Then the result should be (3/5)*100 as 2 words are not matching that is I and good.
Please tell me how to do this.
here is a code as you want
public class Test {
public static void main(String[] args) {
String str1 = "I am a good boy";
String [] s_str1 = str1.split(" ");
String str2 = "Am a god boy";
String [] s_str2 = str2.split(" ");
int match = 0;
for(int i=0;i<s_str1.length;i++){
for(int j=0;j<s_str2.length;j++){
if(s_str1[i].equalsIgnoreCase(s_str2[j])){
match++;
}
}
}
int result = match*100/s_str1.length; //use length of string which is
your main str
System.out.println(result);
}
}
Try this:
int getCommonWords(String s1, String s2) {
Set<String> set1 = new HashSet<>(Arrays.asList(s1.split(" ")));
Set<String> set2 = new HashSet<>(Arrays.asList(s2.split(" ")));
set1.retainAll(set2);
return set1.size();
}
returns the number of common words between 2 strings. It is case-sensitive.

Android iritiate through string for specific letter

I have a string, and I can detect if it has an # inside it.
if(title.contains("#")){
SpannableString WordtoSpan = new SpannableString(title);
int idx = title.indexOf("#");
if (idx >= 0) {
int wordEnd = title.indexOf(" ", idx);
if (wordEnd < 0) {
wordEnd = title.length();
}
WordtoSpan.setSpan(new ForegroundColorSpan(Color.RED),
idx,
wordEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
holder.txtTitle.setText(WordtoSpan);
} else {
holder.txtTitle.setText(title);
}
So now, if the string has an # it will color it till the end of the word after it with red. This works perfectly. But the problem is, when a string has more than one # it will color only the first # with it word, not the next or the third etc ..
ex. Now:
Notice it ill color only burger with red
I love chicken #burger , cuz they are #delicious.
I want: Notice bother burger and delicious are colored.
I love chicken #burger , cuz they are #delicious .
use title.split("#") to get a array of strings which contains #.
Something like:
String parts = title.split("#");
for(int i = 0; i<parts.length(); i++){
//TODO: do something with the string part
//parts[i], this is a part of the string.
}
You can use the Pattern to find and match words that contain hashtags in a given string.
String text = "I love chicken #burger, because they are #delicious!";
Pattern HASHTAG_PATTERN = Pattern.compile("#(\\w+|\\W+)");
Matcher mat = HASHTAG_PATTERN.matcher(text);
while (mat.find()) {
String tag = mat.group(0);
//String tag will contain the hashtag
//do operations with the hashtag
}

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

How to split a string and get a specific string in 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.

Categories

Resources