I've seen many people do similar to this in order to get the last word of a String:
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
I would like to do similar but get the last few words after the last int, it can't be hard coded as the number could be anything and the amount of words after the last int could also be unlimited. I'm wondering whether there is a simple way to do this as I want to avoid using Patterns and Matchers again due to using them earlier on in this method to receive a similar effect.
Thanks in advance.
I would like to get the last few words after the last int.... as the number could be anything and the amount of words after the last int could also be unlimited.
Here's a possible suggestion. Using Array#split
String str = "This is 1 and 2 and 3 some more words .... foo bar baz";
String[] parts = str.split("\\d+(?!.*\\d)\\s+");
And now parts[1] holds all words after the last number in the string.
some more words .... foo bar baz
What about this one:
String test = "a string with a large number 1312398741 and some words";
String[] parts = test.split();
for (int i = 1; i < parts.length; i++)
{
try
{
Integer.parseInt(parts[i])
}
catch (Exception e)
{
// this part is not a number, so lets go on...
continue;
}
// when parsing succeeds, the number was reached and continue has
// not been called. Everything behind 'i' is what you are looking for
// DO YOUR STUFF with parts[i+1] to parts[parts.length] here
}
Related
I using breakIterator to get each word from a sentence and there is problem when a sentence like "my mother-in-law is coming for a visit" where i am not able to get mother-in-law as a single word.
BreakIterator iterator = BreakIterator.getWordInstance(Locale.ENGLISH);
for (int end = iterator.next(); end != BreakIterator.DONE; start = end, end = iterator.next())
{
String possibleWord = sentence.substring(start, end);
if (Character.isLetterOrDigit(possibleWord.charAt(0)))
{
// grab the word
}
}
As I'm seeing in your code what are you trying to do is to check if the first character in every word are a character or a digit. Every time you use the BreakIterator.getWordInstance() you will always get all the words depending on the boundary rules of the Locale and it is a little hard to accomplish what you want to do with the use of this class until I know, so my advice is this:
String text = "my mother-in-law is coming for a visit";
String[] words = text.split(" ");
for (String word : words){
if (Character.isLetterOrDigit(word.charAt(0))){
// grab the word
}
}
I'm using the speech recognizer to get a voice input from the user, it returns an array of 5 strings which I pass to this method
public int analyzeTag(ArrayList<String> voiceResults,Editor editor, Context context){
for (String match : voiceResults) {
Log.d(TAG, match);
if (match.equalsIgnoreCase(context.getResources().getString(R.string.first_tag))){
editor.append(context.getResources().getString(R.string.first_tag));
return 1;
}
else if (match.equalsIgnoreCase(context.getResources().getString(R.string.second_tag))){
editor.append(context.getResources().getString(R.string.second_tag));
return 1;
}
//etc....(huge list of tags)
//Some tags might also have acceptable variations, example:
else if (match.equalsIgnoreCase("img") || match.equalsIgnoreCase("image")
{
editor.append("img"); //the string to append is always taken from the first variation
}
}
return 0;
}
This method compares the results with a list of tags, the tag list will be pretty big with hundreds of tags so I would like to find the most efficient way to do this operation.
I need help with:
1.Is my way of comparing results the most efficient? Is there a better way? (from the user experience perspective, I don't want users waiting a long time to get a result).
The voice input will be a big part of my app so this method will be called quite often
2.I have a long list of tags, obviously the if(), elseIf() route is gonna be quite repetitive, is there a way to iterate this? Considering the fact that some tags might have variations (even more than 1)and that the variation 1 ("img") will be the same for everyone, but other variations will be locale/language sensitive example: "image" for english users "immagini" for italian users etc.
Text appended to the editor will be always taken from the first variation
How about puting tags in a StringArray and then iterate though the array ?
String[] tags = context.getResources().getStringArray(R.array.tags);
for (String match : voiceResults) {
for (int index = 0; index < tags.length; index++ ) {
if (match.equalsIgnoreCase(tags[index]) {
editor.append(tags[index]);
}
}
}
Here's the doc on StringArray
I have a string like this:
_id:2 thread_id:189 address:0292 m_size:null person:0 date:1372494272447 date_sent:0 protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:Ok. Reply message. service_center:051108 locked:0 sim_id:0 error_code:0 seen:1 _id:1 thread_id:189 address:292 m_size:null person:0 date:1372493695831 date_sent:0 protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body:Test message service_center:null locked:0 sim_id:0 error_code:0 seen:0
I want to retrieve only parts of this string, for example the address:0292 and the body:xyz from the entire string. I want all instances of these two from a very large String (above is just a sample). Let's assume its more than 20000 characters.
How can I achieve this?
Looks like every address is followed by m_size, so use the string.split() function, to split over the keyword address then select the string.substring() (from each string in the resulting array) until reaching the keyword m_size. And repeat the entire thing for the keywords body and service_center. I can't think of any other way.
You are right, it doesn't seem pretty. But it works :)
String[] splitString = string.split(" ");
for (int i = 0; i < splitString.length; i++) {
if (splitString[i].startsWith("body") || splitString[i].startsWith("address"))
Log.i(TAG, "Found: " + splitString[i]);
// Do whatever you need to do
}
What I'm trying to do is find a way I can take the word "camel" for example from a EditText field and make for instance c=2 a=1 m=4 e=5 l=3. Is there anyway I can pull the individual characters from a string and convert them to numbers?
I've tried using "split" to separate each character into an array but I can't figure out how to convert the letters into numbers
so I can do something like:
a=1
b=2
c=3
int temp = (int)(array[1]+array[2]+array[3]+etc...)
using the example of "camel" would equal 15
This is what I have so far:
String name = inputarea.getText().toString();
String[] array = name.split("");
for(int i =0; i < array.length ; i++)
The biggest problem I keep having is if I try to pull from the 7th position in the array and nothing is there. (camel only has 5 characters) then I get a nice big error.
Thank you for any help that can be provided.
Edit: I figured it out after a few hours of playing with it here is my working code:
String firstname = inputarea.getText().toString();
char[] array = firstname.toCharArray();
final char[] array2 = new char[15];
System.arraycopy(array, 0, array2, 0, array.length);
if (array2[0] == 'A' ) {
array2[0] = '1';
}
suggestion:
first, need define all letter, from a-z (A-Z), the ASCII code 'a' to 'z' is 97 to 122, if you want support the upper letter, you need add A-Z.
then, get the letter in the string, u can use this:
for(int i=0;i<string.length();i++){
int number = string.charAt(i);
}
when you get the number size, you can reduce to the base number('a' is 97), you will get the individual number
Does String.charAt() works for you?
As for converting to number, if the numbers are consecutive you can define a fixed string with all the characters you want to map and use String.indexOf(). If not, you can have a parallel array with ints or use a Map.
I am brand new to Java and Android so I am sure this will be an easy question/answer. I know that to find out if a string is equal to another string you use the equal function. In my situation, I am scanning a QR Code where the result of the scan is Similar to "EMPLOYEE~~John Smith~~DIVISION~~Maintenance". I need to know how to do the following:
String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"
if (myJunk[0].equals(val1)){
// Do Something
}
In the example Java Code, myJunk[0] never equals val1. What am I doing wrong?
i've tried this and it works , so try to display the contents variable , probably the problem is in the extras , try to display it in logCat :
String contents = "EMPLOYEE~~John Smith~~DIVISION~~Maintenance";
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
String val1 = myJunk[0];
Toast.makeText(this, "val1 = "+val1, Toast.LENGTH_LONG).show();
Toast.makeText(this, "val2 = "+myJunk[1], Toast.LENGTH_LONG).show();
// Now val1 Should be equal to "EMPLOYEE"
if (myJunk[0].equals(val1)){
Toast.makeText(this, "equals", Toast.LENGTH_LONG).show();
}
Your string is:
EMPLOYEE~~John Smith~~DIVISION~~Maintenance
So after spliting, myJunk[0] will contain EMPLOYEE (notice the space in front of the word EMPLOYEE).
So before comparing , you will need to trim your value
The method i usually use, is to print out my variables when in doubt. So if you are unsure of where the problem is, you could try something like this.
(It requires you to be able to see the output, in logcat for example)
String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
System.out.println("contents is "+contents );
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
System.out.println("Array size is "+myJunk.length);
String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"
for(int i=0; i < myJunk.length; i++) {
System.out.println("String "+i+ "in array is: "+myJunk[i]);
}
//Here i run through the array and print every element.
if (myJunk[0].equals(val1)){
// Do Something
}
It is a bit overkill, but this is mostly to show one way of getting all the information you need to find the problem :)