I am stuck splitting a string into pieces to store the pieces into an ArrayList. I can split the string onto " ", but I'd like to split the string onto "farmersmarket" and store it into an Arraylist. To be able to return one of the indexed pieces of string.
ArrayList<String> indexes = new ArrayList<String>();
String s = file;
for(String substring: s.split(" ")){
indexes.add(substring);
}
System.out.println(indexes.get(2));
Any ideas to split a string on "farmersmarket"?
String[] tokens = yourString.split("farmersmarket");
And afterwards you don't need an Arraylist to get a specific element of the tokens. You can access every token like this
String firstToken = tokens[0];
String secondToken = tokens[1];
If you need a List you can do
List<String> list = Arrays.asList(tokens);
and if it has to be an Arraylist do
ArrayList<String> list = new ArrayList<String>(Arrays.asList(tokens));
Assuming that you still want to return a list of strings when the input string doesn't have the character on which you are splitting, Arrays.asList(inputString.split(" ")) should work.
E.g. Arrays.asList("farmersmarket".split(" ")) would return a list that contains only one element--farmersmarket.
Related
I have a java String of a list of numbers with comma separated and i want to put this into an array only the numbers. How can i achieve this?
String result=",17,18,19,";
First remove leading commas:
result = result.replaceFirst("^,", "");
If you don't do the above step, then you will end up with leading empty elements of your array. Lastly split the String by commas (note, this will not result in any trailing empty elements):
String[] arr = result.split(",");
One liner:
String[] arr = result.replaceFirst("^,", "").split(",");
String[] myArray = result.split(",");
This returns an array separated by your argument value, which can be a regular expression.
Try split()
Assuming this as a fixed format,
String result=",17,18,19,";
String[] resultarray= result.substring(1,result.length()).split(",");
for (String string : resultarray) {
System.out.println(string);
}
//output : 17 18 19
That split() method returns
the array of strings computed by splitting this string around matches of the given regular expression
You can do like this :
String result ="1,2,3,4";
String[] nums = result.spilt(","); // num[0]=1 , num[1] = 2 and so on..
String result=",17,18,19,";
String[] resultArray = result.split(",");
System.out.printf("Elements in the array are: ");
for(String resultArr:resultArray)
{
System.out.println(resultArr);
}
This question already has answers here:
How to separate specific elements in string java
(3 answers)
Closed 9 years ago.
so the method takes two parameters, first is the String you will be splitting, second is the delimiter(where to split at).
So if I pass in "abc|def" as the first parameter and "|" as the second I should get a List that returns "abc, def" the problem I'm having is that my if statement requires the delimiter is in the current string to be accessed. I can't think of a better condition, any help?
public List<String> splitIt(String string, String delimiter){
//create and init arraylist.
List<String> list = new ArrayList<String>();
//create and init newString.
String newString="";
//add string to arraylist 'list'.
list.add(string);
//loops through string.
for(int i=0;i<string.length();i++){
newString += string.charAt(i);
if(newString.contains(delimiter)){
//list.remove(string);
list.add(newString.replace(delimiter, ""));
newString="";
}
}
return list;
}
Badshaah and cmvaxter code for split using builtin function split(regex) won't work. as you pass "|" as a delimiter "sam|ple" it wont be splitted as [sam,ple] because ( | , + , * , ...) are all used in regex for other purposes.
and u can check character by character, if the delimiter is a character
loop(each char)
if(not delim)
append to list[i]
else
increment i, discard char
learning purpose it might be needed in c or c++ (even they 've strtok to split strings) to improve effeciency or to modify something differently. [may split differently not using regex]
Its best to use existing system libraries and functions.
if u want to use your function do something like
write these functions yourself
findpos(delim) // gives position of delimiter found in string
substring(pos,len) //len:size of delimiter
getlist(String str,String delim)
//for each delim found use substring and append to list
use some pattern matching algorithms like KMP or something u know.
Change your whole method to.
public List<String> splitIt(String string, String delimiter){
String[] out = string.split(delimiter);
return Arrays.asList(out);
}
Since you are iterating through the string, your if should be based on the character you are inspecting, instead of invoking contains each time:
public List<String> splitIt(String string, String delimiter){
//create and init arraylist.
List<String> list = new ArrayList<String>();
//create and init newString.
String newString="";
//add string to arraylist 'list'.
list.add(string);
//loops through string.
int lastDelimiter = 0;
for (int i=0; i<string.length(); i++) {
if (delimiter.equals("" + string.charAt(i))) {
list.add(string.substring(lastDelimiter, i));
lastDelimiter = i + 1;
}
}
if (lastDelimiter != string.length())
list.add(string.substring(lastDelimiter, string.length()));
return list;
}
For the sake of learning, I think your original attempt lends itself to a recursive solution. The general idea in this case would be:
If there are no delimiters in the string and it is not empty, return the string as the only element in a new list
Otherwise
find the first occurrence of the delimiter
extract the string from the beginning up to the delimiter, call it 'found'
remove the delimiter
recursively call this method, passing it the remainder of the string and the delimiter
append 'found' to the list returned from #4, and return that list
The String class already supports a split method that I believe does exactly what you are looking to do.
String[] s = "abc|def".split("\\|");
List<String> list = Arrays.asList(s);
If you want to do it yourself, the code might look something like this:
char delim = "|".charAt(0);
String s = "abc|def|ghi";
char[] chars = s.toCharArray();
StringBuilder sb = new StringBuilder();
List<String> list = new ArrayList<String>();
for(char c: chars){
if (c == delim){
list.add(sb.toString());
sb = new StringBuilder();
}
else{
sb.append(c);
}
}
if (sb.length() > 0) list.add(sb.toString());
System.out.println(list);
Given the following string:
423545(50),[7568787(50)],53654656,2021947(50),[021947],2021947(50),[8021947(50)]
I would like to split it and put the contents in a array excluding the square brackets and the numbers in the brackets - i.e the result should be an array that contains the following.
{423545,7568787,53654656,2021947,021947,2021947,8021947}
My attempt so far only works if there are no square brackets:
String str = "342398789, [233434],423545(50),[7568787(500)],53654656,2021947(50),[021947],2021947(150),[8021947(50)]";
String[] listItems = str.split("(\\(\\d+\\))?(?:,|$)")
How can I update the above regex to also extract the numbers that wrapped in square brackets?
The strings I am trying to extract are identifiers for database rows so i need to extract them to retrieve the database row.
You could try this way
String str = "[342398789], [233434] ,423545(50),[7568787(500)],"
+ "53654656,2021947(50),[021947],2021947(150),[8021947(50)]";
String[] listItems = str.replaceFirst("^\\[", "").split(
"(\\(\\d+\\))?\\]?(\\s*,\\s*\\[?|$)");
System.out.println(Arrays.toString(listItems));
output
[342398789, 233434, 423545, 7568787, 53654656, 2021947, 021947, 2021947, 8021947]
try this way:
String str = "342398789, [233434],423545(50),[7568787(500)],53654656,2021947(50),[021947],2021947(150),[8021947(50)]";
String[] listItems = str.replaceAll("\\(\\d+\\)","")replaceAll("\\[","").replaceAll("\\]","").split(",");
I have a phrase on a string and I want to split it on other 5 or more string without spaces.
For example:
String test = "hi/ please hepl meok?";
and I want :
String temp1 = "hi/";
String temp2 = "please";
String temp3 = "help";
String temp4 = "meok?";
I dont want to add that in an array, because I want to split the temp4 to 3 more strings.
eg
->> temp4 after splitting:
temp4 = "me"
temp5 = "ok"
temp6 = "?"
This Question is asked because I want to write a method to decode a String phrase from a LinkedHashMap set with some decodes. Thanks. If my way is wrong please guide me! :)
I dont want to add that in an array, because I want to split the temp4 to 3 more strings. eg
Split the string with String#split, then assign the parts of the resulting array to your individual variables:
String[] parts = theOriginalString.split(" ");
String temp1 = parts[0];
String temp2 = parts[1];
String temp3 = parts[2];
String temp4 = parts[3];
String temp5 = parts[4];
I find the idea of making these separate named variables a bit suspect, but I can see use cases — for instance, if you're about to embark on a bunch of logic where useful names make the code clearer.
Given your string, split() will do the trick
String tokens[] = test.split(" ");
tokens[0] will then be "hi/", tokens[1] will be "please" and so on.
EDIT you're going to be storing your strings in an array first in any case when split is used, use StringTokenizer if you want to loop through them individually.
StringTokenizer st = new StringTokenizer(test);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
How to add a comma separated string to an ArrayList? My string "returnedItems" could hold 1 or 20 items which I'd like to add to my ArrayList "selItemArrayList".
After the ArrayList has been populated, I'd like to later iterate through it and format the items into a comma separated string with no spaces between the items.
String returnedItems = "a,b,c";
List<String> sellItems = Arrays.asList(returnedItems.split(","));
Now iterate over the list and append each item to a StringBuilder:
StringBuilder sb = new StringBuilder();
for(String item: sellItems){
if(sb.length() > 0){
sb.append(',');
}
sb.append(item);
}
String result = sb.toString();
One-liners are always popular:
Collections.addAll(arrayList, input.split(","));
split and asList do the trick:
String [] strings = returnedItems.split(",");
List<String> list = Arrays.asList(strings);
Simple one-liner:
selItemArrayList.addAll(Arrays.asList(returnedItems.split("\\s*,\\s*")));
Of course it will be more complex if you have entries with commas in them.
This can help:
for (String s : returnedItems.split(",")) {
selItemArrayList.add(s.trim());
}
//Shorter and sweeter
String [] strings = returnedItems.split(",");
selItemArrayList = Arrays.asList(strings);
//The reverse....
StringBuilder sb = new StringBuilder();
Iterator<String> iter = selItemArrayList.iterator();
while (iter.hasNext()) {
if (sb.length() > 0)
sb.append(",");
sb.append(iter.next());
}
returnedItems = sb.toString();
If the strings themselves can have commas in them, things get more complicated. Rather than rolling your own, consider using one of the many open-source CSV parsers. While they are designed to read in files, at least OpenCSV will also parse an individual string you hand it.
Commons CSV
OpenCSV
Super CSV
OsterMiller CSV
If the individual items aren't quoted then:
QString str = "a,,b,c";
QStringList list1 = str.split(",");
// list1: [ "a", "", "b", "c" ]
If the items are quoted I'd add "[]" characters and use a JSON parser.
You could use the split() method on String to convert the String to an array that you could loop through.
Although you might be able to skip the looping and parsing with a regular expression to remove the spaces using replaceAll() on a String.
String list = "one, two, three, four";
String[] items = list.split("\\p{Punct}");
List<String> aList = Arrays.asList(items);
System.out.println("aList = " + aList);
StringBuilder formatted = new StringBuilder();
for (int i = 0; i < items.length; i++)
{
formatted.append(items[i].trim());
if (i < items.length - 1) formatted.append(',');
}
System.out.println("formatted = " + formatted.toString());
import com.google.common.base.*;
Iterable<String> items = Splitter.on(",").omitEmptyStrings()
.split("Mango,Apple,Guava");
// Join again!
String itemsString = Joiner.join(",").join(items);
String csv = "Apple, Google, Samsung";
step one : converting comma separate String to array of String
String[] elements = csv.split(",");
step two : convert String array to list of String
List<String> fixedLenghtList = Arrays.asList(elements);
step three : copy fixed list to an ArrayList
ArrayList listOfString = new ArrayList(fixedLenghtList);
System.out.println("list from comma separated String : " + listOfString);
System.out.println("size of ArrayList : " + listOfString.size());
Output :
list of comma separated String : [Apple, Google, Samsung]
size of ArrayList : 3