I have a String array that has individuals names in it (example):
["John Smith", "Ramon Ruiz", "Bill Bradford", "Suzy Smith", "Brad Johnson"]
I would like to write a method that prompts a user to input (in form of String) a name OR portion of a name, and then lists all names that contain the string entered by the user, (I can fix the case issue easily).
ex:
Name: rad (meaning user enters "rad")
Output:
Bill Bradford
Brad Johnson
Does anyone have any ideas on this (one that also preserves white spaces)? If there already is a good example of this, feel free to link me. I was unable to find a good method in API.
I would use
for(String name : names) {
if(org.apache.commons.lang3.StringUtils.containsIgnoreCase(name, stringToLookFor)) {
// Do your thing
}
}
You can use .indexOf() it return -1 if it does not find a subString into a String.
for(String name : myArray)
{
if (name.indexOf("rad") != -1) {
// contains word
}
}
Related
I need split String to array. For exapmle i have string str = "apple fruits money Pacific Ocean".
and I try split to array like this:
String []arr = str.split(" ");
But I need the Pacific Ocean to register in one cell of the array. I can't change the separator, because i get data in this form ("apple fruits money Pacific Ocean").
If we admit that multiple consecutive capitalized words need to be considered as a single word, then you can do:
String []arr = str.split("\\s");
then
`String str = "apple fruits money Pacific Ocean";
String[] arr = str.split("\\s");
String[] finalArr = new String[arr.length];
int i = 0;
for (String word : arr) {
// capitalized
if (Character.isUpperCase(word.charAt(0))) {
// check if previous is capitalized
if (Character.isUpperCase(finalArr[i - 1].charAt(0))) {
finalArr[i - 1] = finalArr[i - 1] + word + " ";
} else {
finalArr[i] = word + " ";
}
} else {
finalArr[i] = word;
}
i++;
}
for (String s : finalArr) {
System.out.println(s);
}
}
}`
will result in:
apple
fruits
money
Pacific Ocean
null
You'll need to filter the nulls though and add some checks (if i-1 exists at all).
You need to change the separator as Elliott Frisch stated in his comment. You're not going to be able to determine whether or not a set of words need to stay together if they contain a space. If your word list were separated by another character (such as a comma) then the problem becomes much easier to solve.
String input = "apples,fruits,money,Pacific Ocean";
String[] arr = input.split(",");
Now your array contains each of the words in input.
The problem as described in the question and comments has no solution.
Consider this:
"banana red apple green apple"
This can be split like this:
["banana", "red", "apple", "green", "apple"]
or like this
["banana", "red apple", "green apple"]
Without semantic / contextual analysis it is impossible to know which is more likely to be correct. And it is impossible to know for sure what the (human) user actually meant.
I can't change the separator, because i get data in this form ("apple fruits money Pacific Ocean").
You need to redesign the form or the input syntax so that your software doesn't need to perform this task. There is no other way ... to always get the correct answer.
Think of it this way. Suppose someone gave you a sequence of words in a foreign language on a piece of paper, and asked you to split them correctly. How would you (a human) solve the problem, assuming that you didn't understand the language, and hadn't been given a dictionary or a set of rules? This is equivalent to the task you are setting the computer ...
This way it's not possible. If the string was joined earlier, try using a character other than space. Maybe the pipe | might be an option.
I am Trying to split this string into array format and trying to store in the field name1,name2.. based on the size of the values and the name filed must have only 26 characters.
Name:
Bommiraj Sitaramanjaneyulu Rajasekhara Srinivasulu Laxminarayana Siva
Venkata Sai
Expected Result: name1= Bommiraj Sitaramanjaneyulu ,name2=Rajasekhara srinivasulu,name3=Laxminarayana Siva Venkata,name4=sai,name5="".
Actual result: name field 1:Bommiraju Rajasekhara Siva,name field 2:Venkata Sai
String Testname=nameFormat(" Bommiraj Sitaramanjaneyulu Rajasekhara Srinivasulu Laxminarayana Siva Venkata Sai ");
String formatedName=name.trim().replaceAll("\\s{2,}", " ");
String[] splitedName = formatedName.split("\\s+");
String name1="";
String name2="";
String name3="";
String name4="";
String name5="";
for (String string : splitedName) {
if (name1.length()==0) {
name1+=string;
}else if (name1.length()>0 && name1.length()<26){
if (string.length()+name1.length()<26) {
name1+=" "+string;
}
}else if (name2.length()==0) {
name2+=string;
}else if (name2.length()>0 && name2.length()<26) {
if (string.length()+name2.length()<26) {
name2+=" "+string;
}
}
}
If you count up the size of the first name, Bommiraju Sitaramanjaneyulu, there are 26 characters and a space. Your if statements are <26 so will only work up to 25 characters without whitespace.
More generally, I would recommend storing the names as a String[] and tracking where you are up to. In your current code, a name might go to string2, but a shorter, later name can go to string1, which I assume is not what you wish to do. What I would recommend, depending on your exact needs, would be to start on string[0], and fill it up until the current string doesn't fit, then move onto string[1] and fill that up, etc.
I am trying to display a list of words that are similar to what the user is typing. For example, if I have a list of words like ["Software Eng 1", "Software Eng 2", "Blah"]
And the user typed S, it would filter to the Software Eng 1 and Software Eng 2. Again, the user types So and it filters to the same two words. But if the user types Soc, it would have nothing. What is the best way to do this? I tried
for (EmployeeName r : list)
{
if (textField.getText().matches(r.getName()))
{
System.out.println(r.getName() + " is similar");
}
else System.out.println("NOPE");
}
But this only seems to be catching the case when textField.getText() is exactly the same
you could use String#startsWith if you're checking whether
any Employees name within the list starts with the text entered.
Example:
for (EmployeeName r : list)
{
if (r.getName().startsWith(textField.getText()))
{
System.out.println(r.getName() + " is similar");
}
}
if you're looking to see if the text entered is contained anywhere within the Employees name
then String#contains would do the job.
you could even use String#indexOf to check if the text entered is contained anywhere within the Employees name.
Example:
for (EmployeeName r : list)
{
if (r.getName().indexOf(textField.getText()) != -1)
{
System.out.println(r.getName() + " is similar");
}
}
You can use contains for example ;
textField.getText().toLowerCase().contains(r.getName().toLowerCase())
I'm trying to implement a smart search feature in my application.
Usecase: The user enters the search term in a textbox
Eg: Find me a christian male 28 years old from Brazil.
I need to be parse the input into a map as follows:
Gender: male
Age: 38
Location: Brazil
Relegion: Christian
Already had a glance on : OpenNLP, Cross Validate, Java Pattern Matching and Regex, Information Extraction. I'm confused which one I need to look deeper into.
Is there any java lib already available for this specific domain?
There's an API that extracts structured information (JSON) from free text: http://wit.ai
You need to train Wit with some examples of what you want to be achieved.
Just an approach (there are many ways to do this I think): split your String in a String[] and process each word as you need:
String str = "Find me a christian male 28 years old from Brazil";
for(String s : str.split(" ")){ //splits your String using space char
processWord(s);
}
Where processWord(s) should do something to determine if s is or not a key word based on your business rules.
EDIT: Well, as many people consider this answer insufficient I'll add some more tips.
Let's say you have a class in which you put some search criteria (assuming you want to get people that match these criteria):
public class SearchCriteria {
public void setGender(String gender){...}
public void setCountry(String country){...}
public void setReligion(String religion){...}
...
public void setWatheverYouThinkIsImportant(String str){...}
}
As #Sotirios pointed in his comment, you may need a pool of matching words. Let's say you can use List<String> with basic matching words:
List<String> gender = Arrays.asList(new String[]{"MALE","FEMALE","BOY","GIRL"...});
List<String> country = Arrays.asList(new String[]{"ALGERIA","ARGENTINA","AUSTRIA"...});
List<String> religion = Arrays.asList(new String[]{"CHRISTIAN","JEWISH","MUSLIM"...});
Now I'll modify processWord(s) a little (assuming this method has access to lists above):
public void processWord(String word, SearchCriteria sc){
if(gender.contains(word.toUpperCase()){
sc.setGender(word.toUpperCase());
return;
}
if(country.contains(word.toUpperCase()){
sc.setCountry(word.toUpperCase());
return;
}
if(religion.contains(word.toUpperCase()){
sc.setReligion(word.toUpperCase());
return;
}
....
}
Finally you need to process user's input:
String usersInput = "Find me a christian girl 28 years old from Brazil"; //sorry I change "male" for "girl" but I like girls :P
SearchCriteria sc = new SearchCriteria();
for(String word : usersInput.split(" "){
processWord(word, sc);
}
// do something with your SearchCriteria object
Sure you can do this so much better. This is only an approach.
If you want to do the search more accurate take a read about Levenshtein's distance. It will help you for example if somebody puts "Brasil" instead "Brazil" or "cristian" instead "christian".
This is a pretty huge area of research in language processing: it's called Information Extraction. If it's Java you want, GATE has pretty extensive support for IE.
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