Need to remove extra square brackets in the string - java

static ArrayList<String> coordinates = new ArrayList<String>();
static String str = "";
static ArrayList scribbles = new ArrayList();
coordinates.add("String to be placed, String not to be placed");
String codChange = coordinates.toString().replaceAll(", ", "");
StringBuffer sb = new StringBuffer(codChange);
sb.insert(1,"m ");
ArrayList aListNumbers = new ArrayList(Arrays.asList(sb.toString()));
System.out.println("Coordinates: " + aListNumbers.toString().replaceAll("\\[|\\]", ""));
scribbles.add(aListNumbers);
str = scribbles.toString();
System.out.println("String: " + str);
OUTPUT:
Coordinates: m String to be placedString not to be placed
String: [[m String to be placedString not to be placed]]
I want the String: to appear with single square brackets like:
String: [m String to be placedString not to be placed]

Since there are two different replacement required.
Use below code
String s = "[[m String to be placedString not to be placed]]";
System.out.println(s.replaceAll("[[","[").replaceAll("]]","]");
If you are sure about always the exact position of [[ is at the beginning and ]] is at end, just use substring as suggested in the other answer in the same SO answer thread.

Related

Why is the replace all method not working?

I am testing out the replaceAll() method of the String class and I am having problems with it.
I do not understand why my code does not replace whitespaces with an empty string.
Here's my code:
public static void main(String[] args) {
String str = " I like pie!#!#! It's one of my favorite things !1!!!1111";
str = str.toLowerCase();
str = str.replaceAll("\\p{Punct}", "");
str = str.replaceAll("[^a-zA-Z]", "");
str = str.replaceAll("\\s+", " ");
System.out.print(str);
}
Output:
ilikepieitsoneofmyfavoritethings
The problem is there are no whitespaces in your String after this:
str = str.replaceAll("[^a-zA-Z]", "");
which replaces all characters that are not letters, which includes whitespaces, with a blank (effectively deleting it).
Add whitespace to that character class so they don't get nuked:
str = str.replaceAll("[^a-zA-Z\\s]", "");
And this line may be deleted:
str = str.replaceAll("\\p{Punct}", "");
because it's redundant.
Final code:
String str = " I like pie!#!#! It's one of my favorite things !1!!!1111";
str = str.toLowerCase();
str = str.replaceAll("[^a-zA-Z\\s]", "");
str = str.replaceAll("\\s+", " ");
System.out.print(str);
Output:
i like pie its one of my favorite things
You may want to add str = str.trim(); to remove the leading space.

Replace String and check for uniqueness within String

I am trying to replace specific string with empty value with in string. But below snippet is not removing spaces. Also is there easy approach to look for uniqueness with in strings separated my delimiter?
String str = "||MGR||RAI MGR||PRE RAI MGR||PRE RAI SPR||PRE SPR||";
String newStr = str.replaceAll("RAI", "");
System.out.println("Updates String is::"+newStr);
Output I am looking for is ||MGR||PRE MGR||PRE SPR||
Thanks
Try:
String newStr = str.replaceAll("RAI ", "").replaceAll(" RAI", "").replaceAll("RAI", "");
--- Edit Update ---
Wait a second, you are doing a number of things here. You're not just doing string replacements, you are also compacting the fields between the || delimiters such that you don't have duplicate fields with the same content.
If you were just stripping the "RAI" then you would have
||MGR||MGR||PRE MGR||PRE SPR||PRE SPR||
So, first, split all your fields into Strings, along the || delimiter. Then strip each string of the undesired "RAI". Add them to a Set<String>, and then rebuild the input string from the items in the Set.
--- original post follows ---
You will get a section with two spaces using the technique you are driving at, that's because "PRE RAI MGR" will compact down to "PRE MGR".
One trick is to replace "RAI " with " ", then replace " RAI" with " " and finally replace "RAI" with ""
Include a space in your replaceAll() regex, then using Java 8, you can remove duplicates. Otherwise, you'd have to manually remove duplicate yourself which is still possible, but why reinvent the wheel (except for learning purposes).
public static void main(String[] args) throws Exception {
String str = "||MGR||RAI MGR||PRE RAI MGR||PRE RAI SPR||PRE SPR||";
// "RAI\\s?" means there may be a single space after "RAI"
String newStr = str.replaceAll("RAI\\s?", "");
System.out.println("Updates String is:: " + newStr);
// Remove duplicates
System.out.println("Duplicates Removed:: " + Arrays.stream(
newStr.split("(?=\\|\\|)"))
.distinct()
.map(s -> (s))
.collect(Collectors.joining()));
}
Results:
Updates String is:: ||MGR||MGR||PRE MGR||PRE SPR||PRE SPR||
Duplicates Removed:: ||MGR||PRE MGR||PRE SPR||
Use
String wordToReplace = "RAI";
String regex = "\\s*\\" + wordToReplace + "\\b\\s*";
str = str.replaceAll(regex, "");
replaceAll method of String takes a regex so you could pass one and use this instead
String newStr = str.replaceAll("\\s?RAI\\s?", "");
[Edit]
You only need to remove the trailing space so get the desired output. Use
String newStr = str.replaceAll("RAI\\s?", "");
Complete code:
String str = "||MGR||RAI MGR||PRE RAI MGR||PRE RAI SPR||PRE SPR||";
String newStr = str.replaceAll("RAI\\s?", "");
Set<String> parts = new LinkedHashSet<String>(Arrays.asList(newStr.split("||")));
StringBuilder sdb = new StringBuilder("||");
for (String part : parts) {
sdb.append(part).append("||");
}
newStr = sdb.toString();
System.out.println("Updates String is::" + newStr);
Replace the string to omit " RAI" or "RAI", split to check the uniqueness of values and create new string with unique values.
String str = "||MGR||RAI MGR||PRE RAI MGR||PRE RAI SPR||PRE SPR";
String newStr = "||";
str = str.replaceAll("( |)RAI", "");
String[] values = str.split("\\|\\|");
//add only unique values to new string
for (int i = 1; i < values.length; i++) {
if(!newStr.contains(values[i].trim())){
newStr += values[i].trim() + "||";
}
}
System.out.println("Updates String is::" + newStr);
Thanks for all your inputs. Based on comments and suggestions I managed to get desired output using below code
String str = "||MGR||RAI MGR||PRE RAI MGR||PRE RAI SPR||PRE SPR||";
String noDupBRole = "||";
String newStr = str.replaceAll("RAI ", "").replaceAll(" RAI", "").replaceAll("RAI", "");
System.out.println("New String is::"+newStr);
Set<String> set = new LinkedHashSet<String>(Arrays.asList(newStr.split(Pattern.quote("||"))));
for(String st : set) {
if(st.isEmpty()) continue;
noDupBRole += st+"||";
}
System.out.println("No Duplicate ::"+noDupBRole);

How can I read a String line by line and replace particular line with another particular String

How can I read String line by line and replace particular line with another particular String?
For example:
String myString = "This" +"\nis" + "\nonly" + "\nthe" + "\nexample";
And I want to read them line by line start from the top and replace each one such "This" ->> "newThis" "is" ->> "newIs" , and so on.
You can use the split method:
String[] yourStringAsArray = myString.split("\n")
Then you can iterate over your array like that:
for(String s : yourStringAsArray){
s.replaceAll("oldValue", "newValue")
}
Well, you can split the String on the "\n" character, replace each element you desire, then piece the string back together like so:
String[] lines = myString.split("\n");
// Replace lines here
StringBuilder sb = new StringBuilder();
for (String line : lines) {
sb.append(line + "\n");
}
// Haven't dealt with the trailing "\n", but I leave that as an exercise to the user.
myString = sb.toString();
If you want, you can store it as a String[] by using:
String[] s_array = myString.split("\n");
Then access each element individually
This solution is based on Java 8 Stream API and lambdas.
public static final String DELIMITER = "\n";
public static final Pattern SPLIT_PATTERN = Pattern.compile(DELIMITER);
public static final Function<String, String> TRANSFORM_STRING = (String text) ->
SPLIT_PATTERN.splitAsStream(text)
.map(s -> "new" + s)
.collect(Collectors.joining(DELIMITER));
public static void main(String[] args) {
final String inputText = "This" + "\nis" + "\nonly" + "\nthe" + "\nexample";
final String outputText = TRANSFORM_STRING.apply(inputText);
System.out.println(outputText);
}

How to replace the string with arraylist elements using java

I have a string and arraylist elements.
For example :
String mystring = handbagging
ArrayList a = [ing, bag,and];
I want to replace the String with the arraylist elements and have it be "h+and+bag+g+ing"
Please suggest any ideas. thanks in advance...
I am not sure if I understand your question. You can use a StringBuilder to build a String from multiple Strings like this:
StringBuilder builder = new StringBuilder();
for(String s : myListWithString) {
builder.append(s);
}
String resultString = builder.toString();
I don't understand what you are trying to do here. But for a head start I am going to share with you a sample code which will give you the output you referred.
Note: this is not an optimized solution.
This will not work if there are duplicate strings
I just tried to give you an algorithm, you can come up with your own solution as you know actually what you want.
do not do these string operations, use stringBuffer or StringBuilder
String mystring = "handbagging";
ArrayList<String> a = new ArrayList<String>();
a.add("ing");
a.add("bag");
a.add("and");
System.out.println(mystring);
for (Iterator<String> iterator = a.iterator(); iterator.hasNext();) {
String string = iterator.next();
if(mystring.contains(string)){
int index = mystring.indexOf(string);
mystring = mystring.substring(0, index) + "+" + string + "+" + mystring.substring(index + string.length());
}
}
if(mystring.endsWith("+")){
mystring = mystring.substring(0, mystring.length() - 1);
}
while(mystring.contains("++")){
mystring = mystring.replace("++", "+");
}
System.out.println( "---" + mystring);

Android - Editing my String so each word starts with a capital

I was wondering if someone could provide me some code or point me towards a tutrial which explain how I can convert my string so that each word begins with a capital.
I would also like to convert a different string in italics.
Basically, what my app is doing is getting data from several EditText boxes and then on a button click is being pushed onto the next page via intent and being concatenated into 1 paragraph. Therefore, I assume I need to edit my string on the intial page and make sure it is passed through in the same format.
Thanks in advance
You can use Apache StringUtils. The capitalize method will do the work.
For eg:
WordUtils.capitalize("i am FINE") = "I Am FINE"
or
WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
Here is a simple function
public static String capEachWord(String source){
String result = "";
String[] splitString = source.split(" ");
for(String target : splitString){
result
+= Character.toUpperCase(target.charAt(0))
+ target.substring(1) + " ";
}
return result.trim();
}
The easiest way to do this is using simple Java built-in functions.
Try something like the following (method names may not be exactly right, doing it off the top of my head):
String label = Capitalize("this is my test string");
public String Capitalize(String testString)
{
String[] brokenString = testString.split(" ");
String newString = "";
for(String s : brokenString)
{
s.charAt(0) = s.charAt(0).toUpper();
newString += s + " ";
}
return newString;
}
Give this a try, let me know if it works for you.
Just add android:inputType="textCapWords" to your EditText in layout xml. This wll make all the words start with the Caps letter.
Strings are immutable in Java, and String.charAt returns a value, not a reference that you can set (like in C++). Pheonixblade9's will not compile. This does what Pheonixblade9 suggests, except it compiles.
public String capitalize(String testString) {
String[] brokenString = testString.split(" ");
String newString = "";
for (String s : brokenString) {
char[] chars = s.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
newString = newString + new String(chars) + " ";
}
//the trim removes trailing whitespace
return newString.trim();
}
String source = "hello good old world";
StringBuilder res = new StringBuilder();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print("Result: " + res.toString().trim());

Categories