How can I type partial letters of a word to find this word?
For example:
I have a string array
String[] s = {"Cartoon", "Cheese", "Truck", "Pizza"};
if I input partial letters, such as "ca","Che" or "piz"
then I can find the whole words for the list.
Thanks
stringValue.contains("string that you wanna search");
.contains will do the job, iterate over the loop and keep adding the words in ArrayList<String> for the matched ones.
This could be a good read on string in java.
.contains is like '%word%' in mysql. There are other functions like .startsWith and .endsWith in java. You may use whatever suits the best.
You could use something like
String userInput = (new Scanner(System.in)).next();
for (String string : s) {
if (string.toLowerCase().contains(userInput.toLowerCase()) return string;
}
Note that this is only going to return the first string in your list that contains whatever the user gave you so it's fairly imprecise.
Try using String#startsWith
List<String> list = new ArrayList<>();
list.add("Apples");
list.add("Apples1214");
list.add("NotApples");
list.stream().map(String::toLowerCase)
.filter(x->x.startsWith("app"))
.forEach(System.out::println);
If you just want the String to be contained, then use String#contains
First cast all your strings upper or lower case and then use startsWith () method.
Assuming you meant
String[] s = {"Cartoon", "Cheese", "Truck", "Pizza"};
The easiest option would be to iterate through your string array and do a .contains on each individual String.
for(int i = 0; i < s.length; i++){
if(s[i].contains("car")){
//do something like add to another list.
}
}
This ofcourse does not take caps into concideration. But this can easily be circumvented with .toLowerCare or .toUpperCase.
Related
I know the normal one to split the sentence by using split function, but the problem is you need to declare how many variables you need,
Example: Fighting,Action,Adventure,Racing,RPG
String[] GameGenreCodeSeparated = GameGenreCodeRAW.split(",");
listGameGenre.add(GameGenreCodeSeparated[0]);
listGameGenre.add(GameGenreCodeSeparated[1]);
listGameGenre.add(GameGenreCodeSeparated[2]);
How to add a list every ',' symbol, so a list can has 5 objects from that sentence dynamically, any solution?
You would want to iterate through your array. Something like the below should work.
String[] GameGenreCodeSeparated = GameGenreCodeRAW.split(",");
for (String GameGenre: GameGenreCodeSeparated ) {
listGameGenre.add(GameGenre);
}
Use built-in method Arrays.asList(GameGenreCodeRAW.split(",")) to avoid manually adding.
#Sungakki You should check which approach is better and in this case, Arrays.asList(GameGenreCodeRAW.split(",")) looks better approach which can help you in the future as well.
The reason is Arrays.asList() is a standard utility method for dealing with Arrays. Writing custom for() loop makes no sense here.
If you are having difficulty in understanding what it is doing them below is further details on this.
Here is how you will use it in your code.
listGameGenre = Arrays.asList(GameGenreCodeRAW.split(","));
Arrays.asList() simply returns a fixed-size list backed by the specified array in our case it is GameGenreCodeRAW.
Here is the official documentation for Arrays.asList() official docs.
I hope you understand my point.
It's better to create a new array or an arraylist because it's gonna be a hot mess trying to split a string but not store any data anywhere else.
Here is how I think it should be:
import java.util.ArrayList;
public class test
{
public static void split(String raw){
ArrayList <String> GameGenreCodeSeparated= new ArrayList<String>();
int splits=0;//how man times have the sentence been splited
int previousSplited=0;//index of the prevoius comma
for(int i=0;i<raw.length();i++){
if(raw.charAt(i)==','){//when comma occurs
if(previousSplited==0){//if this is the first comma
GameGenreCodeSeparated.add(raw.substring(0,i));//add the splited string to the list
previousSplited=i;//record the place where splited
}
else{
GameGenreCodeSeparated.add(raw.substring(previousSplited+1,i));//add the splited string to the list
previousSplited=i;//record the place where splited
}
}
else if (i==raw.length()-1){//if this is the end of the string
GameGenreCodeSeparated.add(raw.substring(previousSplited+1,i));//add the splited string to the list
previousSplited=i;//record the place where splited
}
}
System.out.println(GameGenreCodeSeparated);//print out results;
}
}
Hope this helps!
String text = "In addition, Androids could multitask, whereas iPhones could not at that time. By 2011, Android outsold every other smartphone";
String[] textSeparated = text.split(",");
String first=textSeparated[0];
String second=textSeparated[1];
String Third=textSeparated[2];
String Fourth=textSeparated[3];
P.S : If you don't understand anything from the below I describe, please ask me
I have a Dictionary with the list of words.
And I have String of one word with multiple characters.
Eg: Dictionary =>
String[] = {"Manager","age","range", "east".....} // list of words in dictionary
Now I have one string tageranm.
I have to find all the words in the dictionary which can be made using this string. I have been able to find the solution using create all string using Permuation and verify the string is present in the dictionary.
But I have another solution, but dint know how I can do it in Java using Regex
Algorithm:
// 1. Sort `tageranm`.
char c[] = "tageranm".toCharArray();
Arrays.sort(c);
letters = String.valueOf(c); // letters = "aaegmnrt"
2.Sort all words in dictionary:
Example: "range" => "aegnr" // After sorting
Now If I will use "aaegmnrt".contains("aegnr") will return false. As 'm' is coming in between.
Is there a way to use Regex and ignore the character m and get all the words in dictionary using the above approach?
Thanks in advance.
Here is a possible solution, using the regex-type stated by #MattTimmermans in the comments. It's not very fast though, so there are probably loads of ways to improve this.. I'm also pretty sure there should be libraries for this kind of searches, which will (hopefully) have used performance-reducing algorithms.
java.util.List<String> test(String[] words, String input){
java.util.List<String> result = new java.util.ArrayList<>();
// Sort the characters in the input-String:
byte[] inputArray = input.getBytes();
java.util.Arrays.sort(inputArray);
String sortedInput = new String(inputArray);
for(String word : words){
// Sort the characters of the word:
byte[] wordArray = word.getBytes();
java.util.Arrays.sort(wordArray);
String sortedWord = new String(wordArray);
// Create a regex to match from this word:
String wordRegex = ".*" + sortedWord.replaceAll(".", "$0.*");
// If the input matches this regex:
if(sortedInput.matches(wordRegex))
// Add the word to the result-List:
result.add(word);
}
return result;
}
Try it online (with added DEBUG-lines to see what's happening).
For your inputs {"Manager","age","range", "east"} and "tageranm" it will return ["age", "range"].
EDIT: Doesn't match Manager because the M is in uppercase. If you want case-insensitive matching, the easiest it to convert both the input and words to the same case before checking:
input.getBytes() becomes input.toLowerCase().getBytes()
word.getBytes() becomes word.toLowerCase().getBytes()
Try it online (now resulting in ["Manager", "age", "range"]).
My arraylist consists of an array with a list of strings, each string inside is separated by commas, i want to split one of the strings into substrings divided by the commas, i know how to do it to arrays by using the split method, but im having trouble finding something similar to array lists, heres the code:
String[] widgets2 =
{
"1,John,Smith,John1989#gmail.com,20,88,79,59",
"2,Suzan,Erickson,Erickson_1990#gmailcom,19,91,72,85",
"3,Jack,Napoli,The_lawyer99yahoo.com,19,85,84,87",
"4,Erin,Black,Erin.black#comcast.net,22,91,98,82",
"5,Adan,Ramirez,networkturtle66#gmail.com,100,100,100"
};
ArrayList<String> jim = new ArrayList<String>(Arrays.asList(widgets2));
System.out.println(jim.split(0));
It is similar to what you do with the arrays. Just that the implementation is different. To get the values just loop through them:
List<String> jim = new ArrayList<String>(Arrays.asList(widgets2));
for(String currentString : jim){//ArrayList looping
String[] separatedStrings = currentString.split(",");
for(String separatedString : separatedStrings){//Now its array looping
//Do something now whatever you like to
}
}
If you want to have the index and decide which value to get, use normal for loop using index and use jim.get(index) and use split().
Having said that, what stops you from looping through the List ? It's the common usage of array list - to loop through it :)
String jim_string = jim.toString().replace("[", "");
jim_string.replace("]", "");
String splitted[] = jim_string.split(",");
System.out.println(splitted[0]);
put the below code lines into your code, it'll give your desire output.
int indx=0; //use the index you want to get & split
String tmp = jim.get(indx); // get the string from the ArrayList
if(tmp!=null && !tmp.equals("")){ // null check
for (String retval: tmp.split(";")){ // split & print
System.out.println(retval);
}
}
I'm trying to create a program that can abbreviate certain words in a string given by the user.
This is how I've laid it out so far:
Create a hashmap from a .txt file such as the following:
thanks,thx
your,yr
probably,prob
people,ppl
Take a string from the user
Split the string into words
Check the hashmap to see if that word exists as a key
Use hashmap.get() to return the key value
Replace the word with the key value returned
Return an updated string
It all works perfectly fine until I try to update the string:
public String shortenMessage( String inMessage ) {
String updatedstring = "";
String rawstring = inMessage;
String[] words = rawstring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
for (String word : words) {
System.out.println(word);
if (map.containsKey(word) == true) {
String x = map.get(word);
updatedstring = rawstring.replace(word, x);
}
}
System.out.println(updatedstring);
return updatedstring;
}
Input:
thanks, your, probably, people
Output:
thanks, your, probably, ppl
Does anyone know how I can update all the words in the string?
Thanks in advance
updatedstring = rawstring.replace(word, x);
This keeps replacing your updatedstring with the rawstring with a the single replacement.
You need to do something like
updatedstring = rawstring;
...
updatedString = updatedString.replace(word, x);
Edit:
That is the solution to the problem you are seeing but there are a few other problems with your code:
Your replacement won't work for things that you needed to lowercased or remove characters from. You create the words array that you iterate from altered version of your rawstring. Then you go back and try to replace the altered versions from your original rawstring where they don't exist. This will not find the words you think you are replacing.
If you are doing global replacements, you could just create a set of words instead of an array since once the word is replaced, it shouldn't come up again.
You might want to be replacing the words one at a time, because your global replacement could cause weird bugs where a word in the replacement map is a sub word of another replacement word. Instead of using String.replace, make an array/list of words, iterate the words and replace the element in the list if needed and join them. In java 8:
String.join(" ", elements);
passing 0 as a limit argument prevents trailing empty strings, but how does one prevent leading empty strings?
for instance
String[] test = "/Test/Stuff".split("/");
results in an array with "", "Test", "Stuff".
Yeah, I know I could roll my own Tokenizer... but the API docs for StringTokenizer say
"StringTokenizer is a legacy class that is retained for compatibility
reasons although its use is discouraged in new code. It is recommended
that anyone seeking this functionality use the split"
Your best bet is probably just to strip out any leading delimiter:
String input = "/Test/Stuff";
String[] test = input.replaceFirst("^/", "").split("/");
You can make it more generic by putting it in a method:
public String[] mySplit(final String input, final String delim)
{
return input.replaceFirst("^" + delim, "").split(delim);
}
String[] test = mySplit("/Test/Stuff", "/");
Apache Commons has a utility method for exactly this: org.apache.commons.lang.StringUtils.split
StringUtils.split()
Actually in our company we now prefer using this method for splitting in all our projects.
I don't think there is a way you could do this with the built-in split method. So you have two options:
1) Make your own split
2) Iterate through the array after calling split and remove empty elements
If you make your own split you can just combine these two options
public List<String> split(String inString)
{
List<String> outList = new ArrayList<>();
String[] test = inString.split("/");
for(String s : test)
{
if(s != null && s.length() > 0)
outList.add(s);
}
return outList;
}
or you could just check for the delimiter being in the first position before you call split and ignore the first character if it does:
String delimiter = "/";
String delimitedString = "/Test/Stuff";
String[] test;
if(delimitedString.startsWith(delimiter)){
//start at the 1st character not the 0th
test = delimitedString.substring(1).split(delimiter);
}
else
test = delimitedString.split(delimiter);
I think you shall have to manually remove the first empty string. A simple way to do that is this -
String string, subString;
int index;
String[] test;
string = "/Test/Stuff";
index = string.indexOf("/");
subString = string.substring(index+1);
test = subString.split("/");
This will exclude the leading empty string.
I think there is no built-in function to remove blank string in Java. You can eliminate blank deleting string but it may lead to error. For safe you can do this by writing small piece of code as follow:
List<String> list = new ArrayList<String>();
for(String str : test)
{
if(str != null && str.length() > 0)
{
list.add(str);
}
}
test = stringList.toArray(new String[list.size()]);
When using JDK8 and streams, just add a skip(1) after the split. Following sniped decodes a (very wired) hex encoded string.
Arrays.asList("\\x42\\x41\\x53\\x45\\x36\\x34".split("\\\\x"))
.stream()
.skip(1) // <- ignore the first empty element
.map(c->""+(char)Integer.parseInt(c, 16))
.collect(Collectors.joining())
You can use StringTokenizer for this purpose...
String test1 = "/Test/Stuff";
StringTokenizer st = new StringTokenizer(test1,"/");
while(st.hasMoreTokens())
System.out.println(st.nextToken());
This is how I've gotten around this problem. I take the string, call .toCharArray() on it to split it into an array of chars, and then loop through that array and add it to my String list (wrapping each char with String.valueOf). I imagine there's some performance tradeoff but it seems like a readable solution. Hope this helps!
char[] stringChars = string.toCharArray();
List<String> stringList = new ArrayList<>();
for (char stringChar : stringChars) {
stringList.add(String.valueOf(stringChar));
}
You can only add statement like if(StringUtils.isEmpty(string)) continue; before print the string. My JDK version 1.8, no Blank will be printed.
5
this
program
gives
me
problems