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];
Related
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.
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);
I was wondering what would be the best way to go about removing characters before a comma in a string, as well as removing the comma itself, leaving just the characters after the comma in the string, if the string is represented as 'city,country'.
Thanks in advance
So you want
city,country
to become
country
An easy way to do this is this:
public static void main(String[] args) {
System.out.println("city,country".replaceAll(".*,", ""));
}
This is "greedy" though, meaning it will change
city,state,country
into
country
In your case, you might want it to become
state,country
I couldn't tell from your question.
If you want "non-greedy" matching, use
System.out.println("city,state,country".replaceAll(".*?,", ""));
this will output
state, country
check this
String s="city,country";
System.out.println(s.substring(s.lastIndexOf(',')+1));
I found it faster than .replaceAll(".*,", "")
If what you are interested in is extracting data while leaving the original string intact you should use the split(String regex) function.
String foo = new String("city,country");
String[] data = foo.split(",");
The data array will now contain strings "city" and "country".
More info is available here: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29
This can be done with a combination of substring and indexOf, using indexOf to determine the position of the (first) comma, and substring to extract a portion of the string relative to that position.
String s = "city,country";
String s2 = s.substring(s.indexOf(",") + 1);
You could implement a sort of substring that finds all the indexes of characters before your comma and then all you'd need to do is remove them.
What I want to do is to measure the data of a line on a large string. I am not sure if any has tried this but I have a string which looks like this.
String a =
"This is
kinda
my String"
which would display on android textview as
This is
kinda
my String
Now what I want to achieve is being able get the length of the second line "kinda".
The purpose for this is to be able to set my paging for a book project.
I hope I was clear enough. Thanks for any advice or ideas shared.
Should just be:
a.split("\n")[1].length()
You can use the String function split(String regex)
To split on a "\n"(newline) then use it as a tuple/array and call for any word you want.
Split based on new line indicator.
String lines[] = a.split("\\r?\\n");
int length =0;
if(lines.length >1)
{
length = lines[1].length();
}
I haven't used java in years that being said I'd imagine something like this
String[] temp; //Let's make an array of strings
temp = a.split("\n"); //Split the large string by carriage return
int length = temp[1].length(); //get the length of the 2nd string
Assuming those are \n separating your lines...