I have this code which searches a string array and returns the result if the input string matches the 1st characters of a string:
for (int i = 0; i < countryCode.length; i++) {
if (textlength <= countryCode[i].length()) {
if (etsearch
.getText()
.toString()
.equalsIgnoreCase(
(String) countryCode[i].subSequence(0,
textlength))) {
text_sort.add(countryCode[i]);
image_sort.add(flag[i]);
condition_sort.add(condition[i]);
}
}
}
But i want to get those string also where the input string matches not only in the first characters but also any where in the string? How to do this?
You have three way to search if an string contain substring or not:
String string = "Test, I am Adam";
// Anywhere in string
b = string.indexOf("I am") > 0; // true if contains
// Anywhere in string
b = string.matches("(?i).*i am.*"); // true if contains but ignore case
// Anywhere in string
b = string.contains("AA") ; // true if contains but ignore case
I have not enough 'reputation points' to reply in the comments, but there is an error in the accepted answer. indexOf() returns -1 when it cannot find the substring, so it should be:
b = string.indexOf("I am") >= 0;
Check out the contains(CharSequence) method
Try this-
etsearch.getText().toString().contains((String) countryCode[i]);
You could use contains. As in:
myString.contains("xxx");
See also: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html, specifically the contains area.
Use the following:
public boolean contains (CharSequence cs)
Since: API Level 1
Determines if this String contains the sequence of characters in the CharSequence passed.
Parameters
cs the character sequence to search for.
Returns
true if the sequence of characters are contained in this string, otherwise false
Actually, the default Arrayadapter class in android only seems to search from the beginning of whole words but by using the custom Arrayadapter class, you can search for parts of the arbitrary string. I have created the whole custom class and released the library. It is very easy to use. You can check the implementation and usage from here or by clicking on the link provided below.
https://github.com/mohitjha727/Advanced-Search-Filter
You can refer to this simple example-
We have names " Mohit " and "Rohan" and if We put " M" only then Mohit shows up in search result, but when we put "oh" then both Mohit and Rohan show up as they have the common letter 'oh'.
Thank You.
Related
I have a string which is :
1|name|lastname|email|tel \n
2|name|lastname|email|tel \n
I know that I have to use a loop to display all lines but the problem is that in my assignment
I can't use arrays or other classes than String and System.
Also I would like to sort names by ascending order without using sort method or arrays.
Do I have to use compareTo method to compare two names ?
If that's the case, how do I use compareTo method to sort names.
For example, if compareTo returns 1, that means that the name is greater than the other one. In that case how do I manage the return to sort name properly in the string ?
To display all substrings of the string as in the example, you can just go through all characters one by one and store them in a string. Whenever you hit a delimiter (e.g. | or \n), print the last string.
Here's a thread on iterating through characters of a string in Java:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you also need to sort the names in ascending order without an array, you will need to scan the input many times - sorting N strings takes at least N*log(N) steps. If this is a data structure question, PriorityQueue should do the trick for you - insert all substrings and then pop them out in a sorted fashion :)
building on the previous answer by StoneyKeys, since i do not have the privilege to comment, you can use a simple if statement that when the char is a delimiter, System.out.println() your previous scanned string. Then you can reset the string to an empty string in preparation for scanning the next string.
In java, there are special .equals() operators for strings and chars so when you won't be using == to check strings or char. Do look into that. To reset the value of string just assign it a new value. This is because the original variable points at a certain string ie "YHStan", by making it point at "", we are effectively "resetting" the string. ie scannedstr = "";
Please read the code and understand what each line of code does. The sample code and comments is only for your understanding, not a complete solution.
String str ="";
String value = "YH\nStan";
for (int i=0; i <value.length(); i++) {
char c = value.charAt(i);
String strc = Character.toString(c);
//check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
if (strc.equals("\n")) {
System.out.println(str);
str ="";
continue; // go to next iteration (you can instead use a else if to replace this)
}
//if its not delimiter append to str
str = str +strc;
//this is to show you how the str is changing as we go through the loop.
System.out.println(str);
}
System.out.println(str); //print out final string result
This gives a result of:
Y
YH
YH
S
St
Sta
Stan
Stan
I have a problem with a contains (...) method from List <...> class. I'm trying to check if a expression (that is loaded from user input) already exist in a List, but if I entered same name as twice, it said there's nothing same in the List. Please help, there's source code:
boolean checker;
checker = expressions.contains(line[1]);
if (checker == true) {
System.err.println("This expression has already been declared!");
return index;
}
PS: line[1] is a second index in array from main function that stores user-entered line split by whitespaces. (First index of line need to be always 'var', and second is any word that cannot be twice in the List)
Your list may not have exact same string as provided in the input which may be due to white spaces. Try trimming the input and then call contains
checker = expressions.contains(line[1].trim());
I have a string 4.9.14_05_29_16_21 and I need to get 4.9 only. The numbers vary so I can't simply get the first three elements of this char array. I have to find the right most . and substring it till there.
I'm from Python so I'll show Python approach to this.
def foobar(some_string):
location = some_string.rfind('.')
new_string = some_string[0:location]
return new_string
How would I do this in Java?
Use String#lastIndexOf and String#substring:
int location = someString.lastIndexOf('.');
String newString = someString.substring(0, location);
Also note that I've assumed Java's naming convention (i.e. camelCase). If there can be cases where the input does not include a period, you can check if location is negative and include logic to deal with that case.
You should use the following methods:
String.lastIndexOf(int ch) to get the index
String.substring(int beginindex, int endindex) to
extract the String.
Make sure to put an error check in if the string doesn't contain any ., i.e. lastIndexOf returns -1.
public String getBeforePeriod(String input) {
int index = input.lastIndexOf('.');
return index > -1 ? input.substring(0,index) : input;
}
Use String.indexOf() method to provide one second argument to substring() method.
Here is a link to more info.
http://www.tutorialspoint.com/java/java_string_indexof.htm
Have been at this for a while so I think it's time for some much needed help. I have the following if statement in an action listener('but' - being the Search button that gets clicked for the following to happen).I have an arrayList(used to save data from database) in my class, calling a specific record works perfectly. I am trying to create a search textField(named 'tf' below). I have been able to search only by typing an exact match to what ever is being searched, but I want to be able to use partial matching on any String in tf. Everything that's commented out is different stuff that I have been testing, therefore can be ignored.
The statement:
if( srch.getText().equals("You have chosen to search by movie: " )
... this is used to make sure that the person is searching only when the panel includes this title, as there is a genre search as well on the same panel. Only the title changes.
if(source.equals(but)){
//String b = a.get(0).get(1);
String result = tf.getText();
Pattern pat = Pattern.compile("[a-z]+");
Matcher m = pat.matcher(result);
//boolean bool = m.matches();
int i = 0;
//al.contains(result) && pat.matcher(a.get(i).get()).matches())
// && z.contains(result)
if( srch.getText().equals("You have chosen to search by movie: " )){
for (ArrayList<String> al : a){
if (pat.m(a.get(i).get(0)).matches()){
System.out.println(a.get(i).get(0)); //movie name
System.out.println(a.get(i).get(1)); //movie desc
}
i++;
}
//ta.setText(b);
}
else{
ta.setText("Please try searching by movie");
}
}
In summary, everything works fine. I just need a regex code to find partial matches as well and a way to add that into my loops. I've added as little code as possible as not to waste anyone's time, so please let me know if any other is needed.Many thanks in advance. Eventually any full or partial matches will display the movie name and description.
I think there is no need of regex.
String.contains(String chars) returns true if the source string have any occurrence of the argument string.
For example:
String str = "ABCDEFG";
if(str.contains("CD")){
System.out.println("Present");
}
So I want to search through a string to see if it contains the substring that I'm looking for. This is the algorithm I wrote up:
//Declares the String to be searched
String temp = "Hello World?";
//A String array is created to store the individual
//substrings in temp
String[] array = temp.split(" ");
//Iterates through String array and determines if the
//substring is present
for(String a : array)
{
if(a.equalsIgnoreCase("hello"))
{
System.out.println("Found");
break;
}
System.out.println("Not Found");
}
This algorithm works for "hello" but I don't know how to get it to work for "world" since it has a question mark attached to it.
Thanks for any help!
Take a look:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence)
String.contains();
To get a containsIgnoreCase(), you'll have to make your searchword and your String toLowerCase().
Take a look at this answer:
How to check if a String contains another String in a case insensitive manner in Java?
return s1.toLowerCase().contains(s2.toLowerCase());
This will also be true for:
war of the worlds, because it will find world. If you don't want this behavior, youll have to change your method like #Bart Kiers said.
Split on the following instead:
"[\\s?.!,]"
which matches any space char, question mark, dot, exclamation or a comma (add more chars if you like).
Or do a temp = temp.toLowerCase() and then temp.contains("world").
You dont have to do this, it's already implemented:
IndexOf and others
You may want to use :
String string = "Hello World?";
boolean b = string.indexOf("Hello") > 0; // true
To ignore case, regular expressions must be used .
b = string.matches("(?i).*Hello.*");
One more variation to ignore case would be :
// To ignore case
b=string.toLowerCase().indexOf("Hello".toLowerCase()) > 0 // true