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);
Related
This question already has answers here:
Java generating Strings with placeholders
(12 answers)
Closed 4 years ago.
The client passed me a parameter str = "${param0},${param1}".
I want to replace ${param0} ${param1} with the value I queried from the database.
such as
//str = "${param0},${param1}"
//str = "${param0},${param1}, ${param2}"
//...
public String format(String str) {
String param0 = repository.query0();
//expect
str = "param0,${param1}";
String param1 = repository.query1();
//expect
str = "param0,param1,${param2}";
return str;
}
I know that java.lang.String#replace can solve the problem. But the parameter str is indefinite. It could also be str = "${param0}, ${param1}, ${param2}" or more. Is there any way to satisfy my request?
If you can be confident that it will always be in the format of ${paramX} then you can do the following:
String str = ...;
for (int i = 0; i < results.length; i++)
{
str = str.replace("${param" + i + "}", results[i]);
}
Replace the contents of the for loop and the resutls[i] portion to be however you access the data returned from your query.
If you instead can't dependent on ${paramX} being in sequential order, you can use a more hacky solution by using the following code:
// create a new StringBuilder to reduce concatentation
StringBuilder result = new StringBuilder();
// our warped string input
String str = "${param0}, ${param12}${param1234}${param2}";
// split it anywhere that is formatted with ${paramXXXX}
String[] parts = str.split("\\$\\{param[0-9]{1,}\\}");
// loop through the pieces
for (int i = 0; i < parts.length; i++)
{
// get the parts of the string that are not ${paramXXXX}
result.append(parts[i]);
// the results from the query.
result.append(queryResults[i]); // Replace with the proper way to read your query results
}
The above code should work no matter the input, as long as there are the same number of query results as there are ${paramXXXX} pieces in the input string.
Be sure to replace the code followed by // Replace with ... with the code to read your query results.
Here is an approach using matcher:
String str = "${param0},${param1}, ${param2}";
System.out.println("Matching: "+str);
Pattern regex = Pattern.compile("\\$\\{(\\w+)\\}");
Matcher matcher = regex.matcher(str);
while (matcher.find()){
System.out.println("found: "+matcher.group());
str = matcher.replaceFirst("results");
matcher = regex.matcher(str);
}
System.out.println("Result: "+str);
This is not very efficient, but easy to use. If you have gigabyte-scale computations, consider looping over your input string and compare characters manually.
Update:
Here is a better approach. More efficient and not susceptible for endless loop if results contain the pattern.
String str = "[${param0},${param1}, ${param2}]";
System.out.println("Matching: " + str);
final Pattern regex = Pattern.compile("\\$\\{(\\w+)\\}");
final Matcher matcher = regex.matcher(str);
final StringBuilder sb = new StringBuilder(str.length());
int prevMatch = 0;
while (matcher.find()) {
System.out.println("found: " + matcher.group());
sb.append(str.substring(prevMatch, matcher.start()));
sb.append("results");
prevMatch = matcher.end();
}
sb.append(str.substring(prevMatch, str.length()));
System.out.println("Result: " + sb.toString());
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
}
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 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)
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());