How do I replace multiple items in a list? - java

I have added several characters in a list to replace in a string. Here they are:
List<Character> list = new ArrayList<Character>();
list.add(',');
list.add('?');
list.add(',');
list.add(':');
list.add('-');
list.add('(');
list.add(')');
list.add(';');
list.add('/');
I want to replace all occurrences of the character in the list in a string "s".
s.replaceAll(list, "");
I can't do that, of course, because list is NOT a string. But what can I do instead?
EDIT so if
String s = "I am cool; not good!";
I want the list to recognize that it contains ";" and "!", and replace those characters in the String s with nothing. So the result would be:
"I am cool not good"

Rather than use a List<Character>, I would use a regex:
s.replaceAll("[,?:();/-]","");
If you absolutely must define your characters in a List, convert the List to such a regex first.

Rather than List why not use a regular expression. Otherwise you may be stuck with something like:
StringBuilder mySB = new StringBuilder(myString);
for (Character myChar : list) {
mySB.replace(String.valueOf(myChar), "");
}
myString = mySB.toString();

check out Apache Commons StringUtils.replaceEach((String text,
String[] searchList,
String[] replacementList)) it will allow you to provide a list of values to search for and a list of associated replacements in a single line.
Note: This will throw IndexOutOfBoundsException if the lengths of the search and replacement arrays are not the same

Related

Split a string in Java, but keep the delimiters inside each new string

I can't seem to find an answer for this one. What I want to do is to split a string in Java, but I want to keep the delimiters inside each string. For example, if I had the following string:
word1{word2}[word3](word4)"word5"'word6'
The array of new strings would have to be something like this:
["word1", "{word2}", "[word3]", "(word4)", "\"word5\"", "\'word6\'"]
How can I achieve this throughout Regex or other form? I'm still learning Regex in Java, so I tried some things, as discussed in here for example: How to split a string, but also keep the delimiters?
but I'm not getting the results I expect.
I have this delimiter:
static public final String WITH_DELIMITER = "((?<=%1$s)|(?=%1$s))";
And then this method:
private String[] splitLine() { return tokenFactor.split(String.format(WITH_DELIMITER, "\\(|\\)|\\[|\\]|\\{|\\}|\"|\'")); }
But that code splits the delimiters as individual strings, which is not what I want
Can anyone please help me?!! Thanks!
A solution using Pattern and regex :
I will catch every word alone, or words with one element before and after the String
String str = "word1{word2}[word3](word4)\"word5\"'word6'";
Matcher m = Pattern.compile("(([{\\[(\"']\\w+[}\\])\"'])|(\\w+))").matcher(str);
List<String> matches = new ArrayList<>();
while (m.find())
matches.add(m.group());
String[] matchesArray = matches.toArray(new String[0]);
System.out.println(Arrays.toString(matchesArray));
I gave the way to have it in the an array, bu you can stop with the list
Regex demo

Android Java, replace each letter in a text [duplicate]

I have some strings with equations in the following format ((a+b)/(c+(d*e))).
I also have a text file that contains the names of each variable, e.g.:
a velocity
b distance
c time
etc...
What would be the best way for me to write code so that it plugs in velocity everywhere a occurs, and distance for b, and so on?
Don't use String#replaceAll in this case if there is slight chance part you will replace your string contains substring that you will want to replace later, like "distance" contains a and if you will want to replace a later with "velocity" you will end up with "disvelocityance".
It can be same problem as if you would like to replace A with B and B with A. For this kind of text manipulation you can use appendReplacement and appendTail from Matcher class. Here is example
String input = "((a+b)/(c+(d*e)))";
Map<String, String> replacementsMap = new HashMap<>();
replacementsMap.put("a", "velocity");
replacementsMap.put("b", "distance");
replacementsMap.put("c", "time");
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("\\b(a|b|c)\\b");
Matcher m = p.matcher(input);
while (m.find())
m.appendReplacement(sb, replacementsMap.get(m.group()));
m.appendTail(sb);
System.out.println(sb);
Output:
((velocity+distance)/(time+(d*e)))
This code will try to find each occurrence of a or b or c which isn't part of some word (it doesn't have any character before or after it - done with help of \b which represents word boundaries). appendReplacement is method which will append to StringBuffer text from last match (or from beginning if it is first match) but will replace found match with new word (I get replacement from Map). appendTail will put to StringBuilder text after last match.
Also to make this code more dynamic, regex should be generated automatically based on keys used in Map. You can use this code to do it
StringBuilder regexBuilder = new StringBuilder("\\b(");
for (String word:replacementsMap.keySet())
regexBuilder.append(Pattern.quote(word)).append('|');
regexBuilder.deleteCharAt(regexBuilder.length()-1);//lets remove last "|"
regexBuilder.append(")\\b");
String regex = regexBuilder.toString();
I'd make a hashMap mapping the variable names to the descriptions, then iterate through all the characters in the string and replace each occurrance of a recognised key with it's mapping.
I would use a StringBuilder to build up the new string.
Using a hashmap and iterating over the string as A Boschman suggested is one good solution.
Another solution would be to do what others have suggested and do a .replaceAll(); however, you would want to use a regular expression to specify that only the words matching the whole variable name and not a substring are replaced. A regex using word boundary '\b' matching will provide this solution.
String variable = "a";
String newVariable = "velocity";
str.replaceAll("\\b" + variable + "\\b", newVariable);
See http://docs.oracle.com/javase/tutorial/essential/regex/bounds.html
For string str, use the replaceAll() function:
str = str.toUpperCase(); //Prevent substitutions of characters in the middle of a word
str = str.replaceAll("A", "velocity");
str = str.replaceAll("B", "distance");
//etc.

Getting rid of white-space for each String element in ArrayList

I am trying to get rid of all whitespace in each element of my array list.
I could loop through each element, get the text and use .replace(" ","")
But is there an easier method or approach to this?
There is no easier way to do something to each elements in a list than to go through all elements in the list and do something to each element.
Use a ListIterator to iterate the list and update the values:
ListIterator<String> itr = list.listIterator();
while (itr.hasNext()) {
itr.set(itr.next().replaceAll("\\s", ""));
}
Note that to replace all whitespace (not simply " "), you need to use a regular expression, as demonstrated here.
There is no such better option. One approach with Java 8 would be to map the elements of the list and then collect the result:
import static java.util.stream.Collectors.toList;
List<String> al = Arrays.asList("This is a ", "sentence", "\t with some", "\nwhite \n space ");
al.stream().map(s -> s.replaceAll("\\s", "")).forEach(System.out::println);
List<String> cleaned = al.stream().map(s -> s.replaceAll("\\s", "")).collect(toList());
Note that the \\s in the replaceAll function matches for every whitespace (tabs and linebreaks too) -- not only spaces and not on the first. The simple replace function replaces only the first occurrence of the pattern.
The result of the example would be following:
Thisisa
sentence
withsome
whitespace

Java: String splitting into multiple elements

I am having a difficult time figuring out how to split a string like the one following:
String str = "hi=bye,hello,goodbye,pickle,noodle
This string was read from a text file and I need to split the string into each element between the commas. So I would need to split each element into their own string no matter what the text file reads. Keep in mind, each element could be any length and there could be any amount of elements which 'hi' is equal to. Any ideas? Thanks!
use split!
String[] set=str.split(",");
then access each string as you need from set[...] (so lets say you want the 3rd string, you would say: set[2]).
As a test, you can print them all out:
for(int i=0; i<set.length;i++){
System.out.println(set[i]);
}
If you need a bit more advanced approach, I suggest guava's Splitter class:
Iterable<String> split = Splitter.on(',')
.omitEmptyStrings()
.trimResults()
.split(" bye,hello,goodbye,, , pickle, noodle ");
This will get rid of leading or trailing whitespaces and omit blank matches. The class has some more cool stuff in it like splitting your String into key/value pairs.
str = str.subString(indexOf('=')+1); // remove "hi=" part
String[] set=str.split(",");
I'm wondering: Do you mean to split it as such:
"hi=bye"
"hi=hello"
"hi=goodbye"
"hi=pickle"
"hi=noodle"
Because a simple split(",") will not do this. What's the purpose of having "hi=" in your given string?
Probably, if you mean to chop hi= from the front of the string, do this instead:
String input = "hi=bye,hello,goodbye,pickle,noodle";
String hi[] = input.split(",");
hi[0] = (hi[0].split("="))[1];
for (String item : hi) {
System.out.println(item);
}

How do I fill a new array with split pieces from an existing one? (Java)

I'm trying to split paragraphs of information from an array into a new one which is broken into individual words. I know that I need to use the String[] split(String regex), but I can't get this to output right.
What am I doing wrong?
(assume that sentences[i] is the existing array)
String phrase = sentences[i];
String[] sentencesArray = phrase.split("");
System.out.println(sentencesArray[i]);
Thanks!
It might be just the console output going wrong. Try replacing the last line by
System.out.println(java.util.Arrays.toString(sentencesArray));
The empty-string argument to phrase.split("") is suspect too. Try passing a word boundary:
phrase.split("\\b");
You are using an empty expression for splitting, try phrase.split(" ") and work from there.
This does nothing useful:
String[] sentencesArray = phrase.split("");
you're splitting on empty string and it will return an array of the individual characters in the string, starting with an empty string.
It's hard to tell from your question/code what you're trying to do but if you want to split on words you need something like:
private static final Pattern SPC = Pattern.compile("\\s+");
.
.
String[] words = SPC.split(phrase);
The regex will split on one or more spaces which is probably what you want.
String[] sentencesArray = phrase.split("");
The regex based on which the phrase needs to be split up is nothing here. If you wish to split it based on a space character, use:
String[] sentencesArray = phrase.split(" ");
// ^ Give this space

Categories