Removing special characters from string - java

I want to parse this string into a list and return {1.193493, 54.6333, 2.093077, 31.6235, 6.175355, 21.6479}. How do I get rid of the square brackets???? I used a for loop and replace but it doesn't work.
String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]"
String[] parsed = st.split(",");
for (String next : parsed) {
next.replace("//[", "").replace("//]", "");
}

replace() works with plain Strings, not regex. Therefore you can simply use:
next.replace("[", "").replace("]", "");
Also notice that you need to assign it to some string variable; assigning it to need won't work (won't modify elements in parsed array).
You should actually remove the braces first and split later, like this:
String[] parsed = st.replace("[", "").replace("]", "").split(",");

You can do it all at one time with this regex:
(?:\D*(\d*\.\d*))+

You can do this with one line:
List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
Full code:
package com.stackoverflow;
import java.util.Arrays;
import java.util.List;
public class Demo
{
public static void main(String[] args)
{
String t = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
for(String s : list)
{
System.out.println(s);
}
}
}
Converts string to list of strings and prints it. If you need to convert strings to doubles, use Double.parseDouble(s) in loop.

You could achieve your goal in two steps.
1) Remove all special characters except comma (,)
2) Then split by comma (,)
public static void main(String[] args) {
String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
String[] parsed = st.replaceAll("[^\\d.,]+", "").split(",");
}
Output:

Related

How do I remove the whitespace after each comma in an ArrayList?

I am struggling with removing spaces in an arraylist of strings.
Say the user input is as follows: "I walked my dog", my code outputs this:
[I, walked, my, dog]
I want it to have no spaces as such:
[I,walked,my,dog]
I tried to remove whitespace on each individual string before I add it to the arrayList, but the output still has the spaces.
Scanner input = new Scanner(System.in);
ArrayList<String> userWords = new ArrayList<String>();
ArrayList<String> SplituserWords = new ArrayList<String>();
System.out.println("Please enter your phrase: ");
userWords.add(input.nextLine());
for (int index = 0; index < userWords.size(); index++) {
String[] split = userWords.get(index).split("\\s+");
for (String word : split) {
word.replaceAll("\\s+","");
SplituserWords.add(word);
}
System.out.println(SplituserWords);
I suggest just taking advantage of the built-in Arrays#toString() method here:
String words = input.nextLine();
String output = Arrays.toString(words.split(" ")).replace(" ", "");
System.out.println(output); // [I,walked,my,dog]
When you are writing System.out.println(SplituserWords);, you are implicitly calling ArrayList#toString() which generates the list's string and that includes spaces after commas.
You can instead generates your own string output, for example with:
System.out.println("[" + String.join(",", SplituserWords) + "]");
If you insist on using List, it will do it for you.
String input = "I walked my dog";
List<String> SplitUserWords = Arrays.asList(input.split(" "));
String output = SplitUserWords.toString().replace(" ", "");
System.out.println(output); //[I,walked,my,dog]
I tried to remove whitespace on each individual string before I add it to the arrayList, but the output still has the spaces.
That won't work because that isn't the problem. The issue is that it is the list implementation that formats the output for you inserts a space after each comma. It does this in the toString() method. To avoid having to explicitly call replace each time you can also do it like this by overidding toString() when you create your List.
List<String> myList = new ArrayList<>(List.of("I","walked","my", "dog")) {
#Override
public String toString() {
// use super to call the overidden method to format the string
// then remove the spaces and return the new String
return super.toString().replace(" ", "");
}
};
System.out.println(myList);
myList.addAll(List.of("and", "then","fed", "my", "cat"));
System.out.println(myList);
prints
[I,walked,my,dog]
[I,walked,my,dog,and,then,fed,my,cat]
You can also subclass ArrayList as follows. Here I have added the three constructors that ArrayList implements. Note that is is a somewhat extreme solution and may not be worth it for occasionally reformatting of the output. I included it for your consideration.
class MyArrayList<E> extends ArrayList<E> {
public MyArrayList() {
super();
}
public MyArrayList(int capacity) {
super(capacity);
}
public MyArrayList(Collection<? extends E> c) {
super(c);
}
#Override
public String toString() {
return super.toString().replace(" ", "");
}
}
And it would work like so.
MyArrayList<String> myList = new MyArrayList<>(List.of("This", "is", "a","test."));
System.out.println(myList);
prints
[This,is,a,test.]

Java How to convert a String into an List?

I have a String, which can have an multiple number of words which are dot separated.
String s = "text.text1.text2.text3";
I want to generate a List which adds a Element for each word in the String.
List<String> list= Arrays.asList(s.split("/./")); generates just 1 Element.
Is there a fast way to do this?
String#split is the way to go here, except that you want to split on the regex pattern \. by itself, as Java's regex API does not take delimiters:
String s = "text.text1.text2.text3";
List<String> elements = Arrays.asList(s.split("\\."));
System.out.println(elements); // [text, text1, text2, text3]
Just the token is wrong, here is the correct code:
import java.util.*;
public class SeperateString {
public static void main(String[] args) {
String s = "text.text1.text2.text3";
List<String> list= Arrays.asList(s.split("\\."));
System.out.println(list);
}
}
And here is the output:
[text, text1, text2, text3]

Java Streams: Is there a cleaner way of doing this?

I am using streams to concatenate a series of strings and add commas between them, but there must be no comma at the beginning or the end of the result string.
import java.util.Arrays;
import java.util.List;
public class QuestionNine {
public static void main(String[] args) {
new QuestionNine().launch();
}
public void launch(){
List<String> words = Arrays.asList("Hello", "Bonjour", "engine", "Hurray", "What",
"Dog", "boat", "Egg", "Queen", "Soq", "Eet");
String result = (words.stream().map(str -> str + ",").reduce("", (a,b) -> a + b));
result = result.substring(0, result.length() -1); //removes last comma
System.out.println(result);
}
}
Instead of using the String.substring() method at the end to get rid of the last comma, is there a way i could have deleted the last comma within the stream pipeline?
The usual idiom is to use the joining Collector with Streams.
String res = words.stream().collect(Collectors.joining(","));
Although you can use String.join in your case since you are directly dealing with an Iterable.
String res = String.join(",", words);
The problem with your approach is that the mapping function you apply impose that there will be a comma at the end of each word. You could get rid of this mapping; and apply the reduce function such that you get the desired output:
.stream().reduce("", (a,b) -> a.isEmpty() ? b : a+","+b);
but I don't recommend this.
Yes, you can use Collectors.joining() here:
String joined = words.stream().collect(Collectors.joining(", "));
Or, also as noted from comments, you can use newly added String.join(CharSequence, Iterable) method.
String joined = String.join(", ", words);

Replacing null String to empty String

I have a small problem, but it's hard for me to solve it.
I have built a String that is a collection of some object's attributes, constructed and delimited by ||. But whenever I have some null attribute, it keeps on printing null, I want to replace null with empty string.
For example, for the input
ADS||abc||null||null
I want it to become
ADS||abc||||
I tried these two, but they didn't work:
string.replace(null,"")
string.replace("null","")
Can someone please help?
Since Strings are immutable, you should assign your String variable to the result of the replace method.
String str = "ADS||abc||null||null to become ADS||abc||||";
str = str.replace("null", "");
System.out.println(str);
Output:
ADS||abc|||| to become ADS||abc||||
Do you mean below code?
String[] names = new String("ADS||abc||null||null to become ADS||abc||||").split("\\|\\|");
List<String> list = new ArrayList<>();
for (String name : names) {
list.add(name.replace("null", ""));
}
This works fine.
public static void main(String[] args) {
String s = "ADS||abc||null||null";
s = s.replace("null", "");
System.out.println(s);
}
Output
ADS||abc||||
you forgot that string is immutable, add this to your code:
String string = string.replace("null","");

How to sort this string and rebuild the same sorted string again

How can I sort values in this string based on the integral parts i.e.
Input:
[160,190];[650,790];[901,974];[401,540];[60,90];
O/p:
[60,90];[160,190];[401,540];[650,790];[901,974];
Obviously a regular sort must do in this case but I am not sure about
where should I trim the strings compare and rebuild the exact string
with optimized approach.
I'd implement the Comparator interface; a class holding both values of a pair and then:
parse the string using ';' as delimeter and put it in holder class
put all of the holder objects into a List
sort the list using the implemented comparator
Using Guava instead of reimplementing most of the necessary steps.
The first part, parsing the string and converting it to a list of integers will be much nicer, once Lambda expressions can be used.
import static com.google.common.base.CharMatcher.anyOf;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.transform;
import java.util.Collections;
import java.util.List;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
public class StrangeSort {
public static void main(String[] args) {
String input = "[160,190];[650,790];[901,974];[401,540];[60,90]";
Splitter splitter = Splitter.on(anyOf("[],;")).omitEmptyStrings();
// This will be so much nicer with Lambda Expressions
List<Integer> list = newArrayList(transform(newArrayList(splitter.split(input)),
new Function<String, Integer>() {
#Override
public Integer apply(String arg0) {
return Integer.valueOf(arg0);
}}));
// Sort the list
Collections.sort(list);
// Print the list
String output = Joiner.on(';').join(Iterables.partition(list, 2));
System.out.println(output);
}
}
If you need to get rid of the whitespace in the output, you can print output.replaceAll(" ", "");
If each [] specifies a unique range of values, you can extract all numbers, sort them and then construct the resultant string back by grouping two elements in each [].
Pattern pattern = Pattern.compile("(\\d+)");
Matcher matcher = pattern.matcher(s);
Set<Integer> numbers = new TreeSet<>();
while(matcher.find()) {
numbers.add(Integer.parseInt(matcher.group(1)));
}
Next step would be to iterate over numbers and use the current and next index to form the resultant string.
An even better approach is to split the string on ; and use #Sergey N Lukin's Comparator to sort the values
String s = "[160,190];[650,790];[901,974];[401,540];[60,90];";
String[] values = s.split(";");
Set<String> sortedValues = new TreeSet<>(new TokensComparator());
sortedValues.addAll(Arrays.asList(values));
Eventually, join the set's elements with a semi-colon(;) using a loop or Google Guava's Joiner
Joiner.on(';').join(sortedValues);
The normal approach is to split the string by the delimiting character (;) and insert the elements into a sorted set (e.g., TreeSet). Then you can simply iterate over the set and join the elements into a string using the delimiter again. Since you need to sort numerically, you have to implement a Comparator and pass an instance to the TreeSet constructor.
The benefit of this approach is that there is no need for an external sort. The collection will maintain the values in sorted order so you simply iterate over the collection to recover the sorted elements.
Simple example:
import java.util.*;
public class Main {
public static void main(String[] args){
String s="[160,190];[650,790];[901,974];[401,540];[60,90]";
String[] stringArray = s.split(";");
Arrays.sort(stringArray,new TokensComparator());
String newString=Main.join(stringArray,";");
System.out.print(newString);
}
static String join(String[] stringArray, String delimiter) {
StringBuilder builder = new StringBuilder();
for (int i=0; i<stringArray.length; i++) {
builder.append(stringArray[i]);
builder.append(delimiter);
}
return builder.toString();
}
static class TokensComparator implements Comparator<String> {
public int compare(String s1, String s2) {
String token1 = s1.substring(1,s1.length()-1).split(",")[0];
String token2 = s2.substring(1,s2.length()-1).split(",")[0];
return Integer.compare(Integer.parseInt(token1),Integer.parseInt(token2));
}
}
}

Categories

Resources