Java: Find string in array list - java

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);
}
}

Related

How to partial match with a string?

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.

Cannot divide a long string into pieces

There is a long string- "sourceMeaning" which consists of some sentences retrieved from a SQLiteDatabase. I used "&" to separate the sentences like below:
SentenceA&SentenceB&SentenceC .....
After the long string has been retrieved, the string will be divided to:
SentenceA
SentenceB
SentenceC
....
I used a String array (Meanings) to store the divided sentences and applied the following codes to finish the task, but it throws StringIndexOutOfBoundsException when executing...
String sourceMeaning=c.getString(1);
Log.w("SourceMeaning",sourceMeaning);
String[] Meanings=new String[]{};
int j=0;
for (int i=0;i<=sourceMeaning.length();i++){
if (sourceMeaning.charAt(i)!='&'){
Meanings[j]=Meanings[j]+sourceMeaning.charAt(i);
Log.w("Translated",Meanings[j]);
} else {
j+=1;
}
}
How to divide the sentences without error?
You can use the split() and then iterate through the generated array:
String[] sentences = sourceMeaning.split("&");
for (String sentence: sentences) {
//iterate through each one of the sentences, i.e:
//SentenceA, SentenceB, ....
}
you should split the initial string in this way
String sourceMeaning=c.getString(1);
Log.w("SourceMeaning",sourceMeaning);
String[] meanings = sourceMeaning.split("&");
you will have everything in that array
i'm not sure to totally get what you are trying to do, so i'm gonna answer this question:
How to divide the sentences without error?
Using the split method of the String Class in Java
Here
You can use str.split() method to get your string to array like :
String[] Meanings = sourceMeaning.split("&");

how to sort substrings separated by blanks in a string

how can the elements inside a String separated by blank spaces be sorted.I have the following String:
temp = abcd bcda gfre dfgre fwft efwe
//temp.size() gives 30
//after the sort temp should look like ie temp = abcd bcda dfgre efwe fwft gfre
I need to sort the elements in temp in the least possible time.Please note that the size of temp that i am dealing with is of the order of 10 to the power 7.I forgot to mention that i have tried Collections.sort and Array.sort which are taking too much time than required.What i require is a faster algorithm than that?
Split the String using .split(seperator)
Sort using Collections Arrays.sort()
String [] array = temp.split("\\s+"); // split by whitespace
Arrays.sort(array); // sort using mergesort with insertionsort
StringBuilder sb = new StringBuilder(temp.length());
for(String s : array){
sb.append(s).append(" ");
}
temp = sb.toString(); // assign temp the new string

How do I modify my arrayList as I enter it into another arrayList such that to remove and change it's values?

I have made an array list that stores words from a text file. but now I need to make a separate array list that only takes the letters from the words in the file reverts them to lower case and removes all punctuation in the words or around it. So basically it restores all the words with all the mentioned elements removed from them.
List<String> grams = new ArrayList<String>();
for(String gram : words){
gram = gram.trim();
for(int i=0,int l=gram.size();i<l;++i){ //this line is wrong
const String punChars = ",[]:'-!_().?\/~"; //this line is wrong
if(gram.indexOf(i) != -1){ //this line is wrong
gram.remove(i); //this line is wrong
}
gram.add(gram.remove(0).toLowerCase()); //this line is wrong
}
}
I'm basically trying to read each character in a select string in the array as I put it into the new array list and then if it has any punctuation around or in it I remove it: I try to do this using a const to store the punctuation values and then I check the string with an if statement to remove that position in the string.
Next I try and add the word but remove the uppercase and change it to lowercase.
I'm a little lost and am not sure what I am doing with this bit here...
My interpretation of your problem is that you want to go through a list of words, convert them into lowercase, remove punctuation and then insert them into another list? If that's the case, then I don't see why you need to modify the original list. You can do something like this:
for(String gram : words) {
gram = gram.trim(); //trim string
gram = gram.replaceAll("[^A-Za-z0-9]", ""); //remove any non alphanumeric characters
grams.add(gram); //add to the grams list
}
Why not cycle through each character in the String like this:
for (char c : gram.toCharArray()) {
...
}
Then check to see if your character is in list of excluded characters and if not then lower case it and add it to your output list?

How to prevent java.lang.String.split() from creating a leading empty string?

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

Categories

Resources