Create ArrayList from comma separated String without whitespace - java

Say I have a String with randomly placed spaces and commas around other characters.
String str = "item1 , it em 2, ite m 3"
How do I get an ArrayList with the items like
[item1, item2, item3]

Use the following:
String str = "item1 , it em 2, ite m 3"
String[] splitArray = str.split(",");
ArrayList<String> list = new ArrayList<String>();
for (String s:splitArray)
{
list.add(s.replace(" ", ""));
}

just for fun :-)
import org.apache.commons.lang3.StringUtils;
String inputString = "item1 , it em 2, ite m 3";
List<String> stringList = Arrays.stream(StringUtils.deleteWhitespace(inputString).split(",")).collect(Collectors.toList());

Here's another solution
//Given string
String str = "item1 , it em 2, ite m 3";
//Match one or more occurrence of space in the string and replace by empty
String pattern = "\\s+";
str = str.replaceAll(pattern, "");
//Split by , and convert to ArrayList
List<String> items = Arrays.asList(str.split(","));
for(String temp: items)
System.out.println(temp);

Using Java 8 's parallelSetAll
String str = "item1 , it em 2, ite m 3";
String[] stringlist = str.split(",");
Arrays.parallelSetAll(stringlist, (i) -> stringlist[i].replaceAll(" ",""));

Related

Convert ArrayList of Integers to String Java

I want to convert an ArrayList of Integers to a single string.
For example:
List<Integers> listInt= new ArrayList();
String str = "";
listInt.add(1);
listInt.add(2);
listInt.add(3);
// I want the output to be: str = "123";
String numberString = listInt.stream().map(String::valueOf)
.collect(Collectors.joining(""));
//You can pass a delimiter if you want to the joining() function, like a comma. ","
Try this, the simplest way:
List<Integer> listInt = Arrays.asList(1,2,3);
String str = "";
StringBuilder builder = new StringBuilder();
for(Integer item : listInt)
builder.append(item);
str = builder.toString();
System.out.println(str);

Extract String(s) from big String selected by special characters

Let's say I have a String like this:
Hey man, my name is Jason and I like Pizza. #Pizza #Name #Cliche
My question is how to extract all the strings that start with # and put them to another string together?
Check out this tutorial on regex
Try
Matcher matcher = Pattern.compile("(\\s|^)#(\\S*)").matcher(string);
while(matcher.find()){
System.out.println(matcher.group(2));
}
EDIT:
As you wanted the other strings as well, you may try
Matcher matcher = Pattern.compile("(\\s|^)#(\\S*)|(\\S+)").matcher(string);
StringJoiner hashfull = new StringJoiner(" ");
StringJoiner hashless = new StringJoiner(" ");
while(matcher.find())
if(matcher.group(2) != null)
hashfull.add(matcher.group(2));
else if(matcher.group(3) != null)
hashless.add(matcher.group(3));
System.out.println(hashfull);
System.out.println(hashless);
I found this code working very well for me because I wanted also the rest of the string. Thanks to #Pshemo and #Mormod for helping me with this. Here is the code:
String string = "Hello my name is Jason and I like pizza. #Me #Pizza";
String[] splitedString = string.split(" "); //splits string at spaces
StringBuilder newString = new StringBuilder();
StringBuilder newString2 = new StringBuilder();
for(int i = 0; i<splitedString.length; i++){
if(splitedString[i].startsWith("#")){
newString.append(splitedString[i]);
newString.append(" "); }
else{
newString2.append(splitedString[i]);
newString2.append(" ");
}
}
System.out.println(newString2);
System.out.println(newString);
Maybe you search for something like this:
String string = "ab cd ef"
String[] splitedString = string.split(" "); //splits string at spaces
String newString = "";
for(int i = 0; i<splitedString; i++){
if(splitedString[i].startsWith("#")){
newString += splitedString[i];
}
}
mormod

How to convert String[] to String and vice versa in Android

I want to convert a String Array to String so that later on while retrieving I can parse String to String[] with the help of (,) separator.
String [] ------------> String
//and later
String ---------------> String[]
Can someone guide on how to do this?
for (int i = 0; i <= count; i++) {
Log.d(TAG, "arrayData == " +arrayData[i]);
// Joining:
String joined = String.join(",", arrayData);
//This will give error "The method join(String, String[]) is undefined for the type String"
}
You can use String.join StringBuilder and String.split:
// Joining:
String joined = String.join(",", stringArr);
StringBuilder buffer = new StringBuilder();
for (String each : stringArr)
buffer.append(",").append(each);
String joined = buffer.deleteCharAt(0).toString();
// Splitting:
String[] splitted = joined.split(",");

Regex to split string

I have this code which prints:
[( ?Random = <http://www.semanticweb.org/vassilis/ontologies/2013/5/Test#Hello> ), ( ?Random = <http://www.semanticweb.org/vassilis/ontologies/2013/5/Test#Bye> )]
I tried to split at [#] but it didnt work.
What should i put in split so that I can get as a result the part after # only: Hello, Bye
Query query = QueryFactory.create(queryString);
QueryExecution qe= QueryExecutionFactory.create(query, model);
ResultSet resultset = qe.execSelect();
ResultSet results = ResultSetFactory.copyResults(resultset);
final ResultSet results2 = ResultSetFactory.copyResults(results);
System.out.println( "== Available Options ==" );
ResultSetFormatter.out(System.out, results, query);
Scanner input = new Scanner(System.in);
final String inputs;
inputs = input.next();
final String[] indices = inputs.split("\\s*,\\s*");
final List<QuerySolution> selectedSolutions = new ArrayList<QuerySolution>(
indices.length) {
{
final List<QuerySolution> solutions = ResultSetFormatter
.toList(results2);
for (final String index : indices) {
add(solutions.get(Integer.valueOf(index)));
}
}
};
System.out.println(selectedSolutions);
If I understand correctly, you only want to extract "Hello" and "Bye" from your input String through regex.
In which case, I would just use iterative matching of whatever's in between # and >, as such:
// To clarify, this String is just an example
// Use yourScannerInstance.nextLine to get the real data
String input = "[( ?Random = <http://www.semanticweb.org/vassilis/ontologies/2013/5/Test#Hello> ), "
+ "( ?Random = <http://www.semanticweb.org/vassilis/ontologies/2013/5/Test#Bye> )]";
// Pattern improved by Brian
// was: #(.+?)>
Pattern p = Pattern.compile("#([^>]+)>");
Matcher m = p.matcher(input);
// To clarify, printing the String out is just for testing purpose
// Add "m.group(1)" to a Collection<String> to use it in further code
while (m.find()) {
System.out.println(m.group(1));
}
Output:
Hello
Bye
You can try this
String[] str= your_orginal_String.split(",");
Then you can take the parts after # as follows
String[] s=new String[2];
int j=0;
for(String i:str){
s[j]=i.split("#",2)[1];
j++;
}
You may need some formatting. for resulting String[] s as follows
String str = "[( ?Random = <http://www.semanticweb.org/vassilis
/ontologies/2013/5/Test#Hello> ), ( ?Random =
<http://www.semanticweb.org/vassilis/ontologies/2013/5/Test#Bye> )]";
String[] arr = str.split(",");
String[] subArr = new String[arr.length];
int j = 0;
for (String i : arr) {
subArr[j] = i.split("#", 2)[1].replaceAll("\\>|\\)|\\]", "");
j++;
}
System.out.println(Arrays.toString(subArr));
Out put:
[Hello , Bye ]
Try the regular expression:
(?<=#)([^#>]+)
e.g.:
private static final Pattern REGEX_PATTERN =
Pattern.compile("(?<=#)([^#>]+)");
public static void main(String[] args) {
String input = "[( ?A = <http://www.semanticweb.org/vassilis/ontologies/2013/5/Test#Hello> ), ( ?A = <http://www.semanticweb.org/vassilis/ontologies/2013/5/Test#World> )]";
Matcher matcher = REGEX_PATTERN.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
Output:
Hello
World

Split mathematical string in Java

I have this string: "23+43*435/675-23". How can I split it? The last result which I want is:
String 1st=23
String 2nd=435
String 3rd=675
String 4th=23
I already used this method:
String s = "hello+pLus-minuss*multi/divide";
String[] split = s.split("\\+");
String[] split1 = s.split("\\-");
String[] split2 = s.split("\\*");
String[] split3 = s.split("\\/");
String plus = split[1];
String minus = split1[1];
String multi = split2[1];
String div = split3[1];
System.out.println(plus+"\n"+minus+"\n"+multi+"\n"+div+"\n");
But it gives me this result:
pLus-minuss*multi/divide
minuss*multi/divide
multi/divide
divide
But I require result in this form
pLus
minuss
multi
divide
Try this:
public static void main(String[] args) {
String s ="23+43*435/675-23";
String[] ss = s.split("[-+*/]");
for(String str: ss)
System.out.println(str);
}
Output:
23
43
435
675
23
I dont know why you want to store in variables and then print . Anyway try below code:
public static void main(String[] args) {
String s = "hello+pLus-minuss*multi/divide";
String[] ss = s.split("[-+*/]");
String first =ss[1];
String second =ss[2];
String third =ss[3];
String forth =ss[4];
System.out.println(first+"\n"+second+"\n"+third+"\n"+forth+"\n");
}
Output:
pLus
minuss
multi
divide
Try this out :
String data = "23+43*435/675-23";
Pattern pattern = Pattern.compile("[^\\+\\*\\/\\-]+");
Matcher matcher = pattern.matcher(data);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
list.add(matcher.group());
}
for (int index = 0; index < list.size(); index++) {
System.out.println(index + " : " + list.get(index));
}
Output :
0 : 23
1 : 43
2 : 435
3 : 675
4 : 23
I think it is only the issue of index. You should have used index 0 to get the split result.
String[] split = s.split("\\+");
String[] split1 = split .split("\\-");
String[] split2 = split1 .split("\\*");
String[] split3 = split2 .split("\\/");
String hello= split[0];//split[0]=hello,split[1]=pLus-minuss*multi/divide
String plus= split1[0];//split1[0]=plus,split1[1]=minuss*multi/divide
String minus= split2[0];//split2[0]=minuss,split2[1]=multi/divide
String multi= split3[0];//split3[0]=multi,split3[1]=divide
String div= split3[1];
If the order of operators matters, change your code to this:
String s = "hello+pLus-minuss*multi/divide";
String[] split = s.split("\\+");
String[] split1 = split[1].split("\\-");
String[] split2 = split1[1].split("\\*");
String[] split3 = split2[1].split("\\/");
String plus = split1[0];
String minus = split2[0];
String multi = split3[0];
String div = split3[1];
System.out.println(plus + "\n" + minus + "\n" + multi + "\n" + div + "\n");
Otherwise, to spit on any operator, and store to variable do this:
public static void main(String[] args) {
String s = "hello+pLus-minuss*multi/divide";
String[] ss = s.split("[-+*/]");
String plus = ss[1];
String minus = ss[2];
String multi = ss[3];
String div = ss[4];
System.out.println(plus + "\n" + minus + "\n" + multi + "\n" + div + "\n");
}

Categories

Resources