I have an array like this: ["one", two"]
If I make array.toString().replace("[", "").replace("]", "").trim();,
I will have: "one, two"
What I really want is "one", "two"
How can I do this?
EDIT:
This is a simple program to explain my question:
ArrayList<String> array = new ArrayList<>();
array.add("one");
array.add("two");
String stringArray = array.toString().replace("[", "").replace("]", "");
Gson gson = new Gson();
String json = gson.toJson(stringArray);
System.out.println(json);
You can try with
array.stream().map(s->"\""+s+"\"").collect(Collectors.joining(", "));
which will first surround each strings with quotes, then join them using ,
For Java 7
String delimiter = ", ";
StringBuilder sb = new StringBuilder();
if (!array.isEmpty()) {
sb.append('"').append(array.get(0)).append('"');
}
for (int i = 1; i < array.size(); i++) {
sb.append(delimiter).append('"').append(array.get(i)).append('"');
}
String result = sb.toString();
Well, just replace comma's with some extra "'s
array.toString().replace("[", "").replace("]", "").trim().replace(", ", "\", \"")
(Not tested, but you get the idea)
Related
I want to extract specific substrings from a string:
String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB"+
"info2 info2ContentA";
The result should be:
String info1 ="info1ContentA info1ContentB";
String info2 ="info2ContentA";
String info3 ="info3ContentA info3ContentB";
For me it's very difficult to extract the informations, because sometimes after "info" their are one, two or more content informations. Another problem that occurs is, that the order of info1, info2 etc. is not sorted and the "real data" doesn't contain a ascending number.
My first idea was to add info1, info2, info3 etc to an ArrayList.
private ArrayList<String> arr = new ArrayList<String>();
arr.add("info1");
arr.add("info2");
arr.add("info3");
Now I want to extract the substring with the method StringUtils.substringBetween() from Apache Commons (https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4):
String result = StringUtils.substringBetween(source, arr.get(0), arr.get(1));
This works, if info1 is in the string before info2, but like I said the "real data" is not sorted.
Any idea how I can fix this?
Split those string by space and then use String's method startsWith to add the part to proper result string
Map<String, String> resultMap = new HashMap<String, String>();
String[] prefixes = new String[]{"info1", "info2", "info3"};
String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB"+" info2 info2ContentA";
String[] parts = source.split(" ");
for(String part : parts) {
for(String prefix : prefixes) {
if(part.startsWith(prefix) {
String currentResult = (resultMap.containsKey(prefix) ? resultMap.get(prefix) + part + " " : part);
resultMap.put(prefix, currentResult);
}
}
}
Also consider using StringBuilder instead of adding string parts
If you cannot be sure that parts will be embraces with spaces you can change at the beginning all part to <SPACE>part in your source string using String replace method
You can use a regular expression, like this:
String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB info2 info2ContentA";
for (int i = 1; i < 3; i++) {
Pattern pattern = Pattern.compile("info" + i + "Content[A-Z]");
Matcher matcher = pattern.matcher(source);
List<String> matches = new ArrayList<>();
while (matcher.find()) {
matches.add(matcher.group());
}
// process the matches list
}
Is there any solution on how to replace words in string without using String replace?
As you all can see this is like hard coded it. Is there any method to make it dynamically? I heard that there is some library file able to make it dynamically but I am not very sure.
Any expert out there able to give me some solutions? Thank you so much and have a nice day.
for (int i = 0; i < results.size(); ++i) {
// To remove the unwanted words in the query
test = results.toString();
String testresults = test.replace("numFound=2,start=0,docs=[","");
testresults = testresults.replace("numFound=1,start=0,docs=[","");
testresults = testresults.replace("{","");
testresults = testresults.replace("SolrDocument","");
testresults = testresults.replace("numFound=4,start=0,docs=[","");
testresults = testresults.replace("SolrDocument{", "");
testresults = testresults.replace("content=[", "");
testresults = testresults.replace("id=", "");
testresults = testresults.replace("]}]}", "");
testresults = testresults.replace("]}", "");
testresults = testresults.replace("}", "");
In this case, you will need learn regular expression and a built-in String function String.replaceAll() to capture all possible unwanted words.
For example:
test.replaceAll("SolrDocument|id=|content=\\[", "");
Simply create and use a custom String.replace() method which happens to use the String.replace() method within it:
public static String customReplace(String inputString, String replaceWith, String... stringsToReplace) {
if (inputString.equals("")) { return replaceWith; }
if (stringsToReplace.length == 0) { return inputString; }
for (int i = 0; i < stringsToReplace.length; i++) {
inputString = inputString.replace(stringsToReplace[i], replaceWith);
}
return inputString;
}
In the example method above you can supply as many strings as you like to be replaced within the stringsToReplace parameter as long as they are delimited with a comma (,). They will all be replaced with what you supply for the replaceWith parameter.
Here is an example of how it can be used:
String test = "This is a string which contains numFound=2,start=0,docs=[ crap and it may also "
+ "have numFound=1,start=0,docs=[ junk in it along with open curly bracket { and "
+ "the SolrDocument word which might also have ]}]} other crap in there too.";
testResult = customReplace(strg, "", "numFound=2,start=0,docs=[ ", "numFound=1,start=0,docs=[ ",
+ "{ ", "SolrDocument ", "]}]} ");
System.out.println(testResult);
You can also pass a single String Array which contains all your unwanted strings within its elements and pass that array to the stringsToReplace parameter, for example:
String test = "This is a string which contains numFound=2,start=0,docs=[ crap and it may also "
+ "have numFound=1,start=0,docs=[ junk in it along with open curly bracket { and "
+ "the SolrDocument word which might also have ]}]} other crap in there too.";
String[] unwantedStrings = {"numFound=2,start=0,docs=[ ", "numFound=1,start=0,docs=[ ",
"{ ", "SolrDocument ", "]}]} "};
String testResult = customReplace(test, "", unwantedStrings);
System.out.println(testResult);
I have an array of String like: "11456811193903(admin 2016-03-01 11:16:23) (Sale)", I want to remove " (Sale)" from the array String. How to replace this in an array of Strings?
Original String:
String[] fileName = {"11456811193903(admin 2016-03-01 11:16:23) (Sale)"};
After replacing:
fileName:11456811193903(admin 2016-03-01 11:16:23)
Bahramdun's solution works perfectly fine, but if you are a fan of Java 8 streams you might want to use this:
String[] fileName = {...};
fileName = Arrays.stream(fileName)
.map(s -> s.replace("(Sale)", ""))
.toArray(size -> new String[size]);
You can try this: If your array has more than one element, then you can loop over the array as shown below. And if it is only one sentence, then you can directly remove the (Scale) and assign it again to the String fileName
String[] fileName = {"11456811193903(admin 2016-03-01 11:16:23) (Sale)"};
for (int i = 0; i < fileName.length; i++) {
fileName[i] = fileName[i].replaceAll("\\(Sale\\)", "");
}
System.out.println("fileName = " + Arrays.toString(fileName));
And it is the result:
fileName = [11456811193903(admin 2016-03-01 11:16:23)]
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.
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);