Is it possible to replace() multiple strings at once?
For example:
String X = new String("I will find cookies");
String newX = X.replace(("will", "won't") + ("I", "You"));
System.out.print(newX);
OUTPUT
You won't find cookies
I know what I did was wrong and will create an error but at least you get my idea of "replacing multiples". If it's possible, what would be the better solution to this?
The simplest answer (I can think of) here is:
String newX = X.replace("will", "won't").replace("I", "You");
This will be find for a simple example like this, but if you're trying to do anything bigger (i.e. many more replacements), you'd be wise to look into regular expressions instead.
You can do a chained call of replace() like below:
String X = new String("I will find cookies");
String newX = X.replace("will", "won't").replace("I", "You");
System.out.print(newX);
Related
How to strip a string like this:
String a = "ItemStack{DIAMOND_HELMET x 1,UNSPECIFIC_META:{meta-type=UNSPECIFIC, display-name=PRO, repair-cost=1}}"
I want to get something like
"Diamond_HELMET 1 UNSPECIFIC PRO"
The methods I have tried is just replacing a bunch of strings, but its a pain in the *** and looks awful. Just wondering if anyone have a better solution/option.
Sorry forgot to add my own code :/
String itemStackStringName = "ItemStack{DIAMOND_HELMET x 1, UNSPECIFIC_META:{meta-type=UNSPECIFIC, display-name=PRO, repair-cost=1}}";
String getItemStacks = itemStackStringName.replace("ItemStack","")
.replace("{","").replace("}", "").replace("UNSPECIFIC_META:", "")
.replace("display-name", "").replace("=","")
.replace("meta-type", "").replace("repair-cost1", "")
.replace("x", "").replace(",","");
System.out.println(getItemStacks);
"DIAMOND_HELMET 1 UNSPECIFIC PRO"
It works, but its just a huge mess.
If you know that's the type your strings are going to be, you can go ahead and do something like this:
String arr[] = a.split("\\{");//you get an array of 3 strings
String someFinalString = arr[1].split("x")[0].trim();//you get "DIAMOND_HELMET"
someFinalString += arr[1].split("x")[1].split(",")[0];
arr = arr[2].split("\\=");//you get an array of 4 strings
someFinalString += " " + arr[1].split(",")[0] + " " + arr[2].split(",")[0];
In the future please post what you tried to do. Splitting something like this will always look awful. You can always make it concise later.
Just a proof this works (and you can figure out by yourself how to get lowercase I guess):
I am writing unit tests now and I need to create a specific string.
I have now defined something like this:
private final String at = "#:";
private String error, effect, one, two, three, four;
in setUp (#Before):
error = RandomStringUtils.randomAlphabetic (3);
one = RandomStringUtils.randomAlphabetic (6);
two = RandomStringUtils.randomAlphabetic (8);
three = RandomStringUtils.randomAlphabetic (2);
four = RandomStringUtils.randomAlphabetic (6);
effect = (error + at + one + at + two + at + three + at + four);
The combination of the strings with the pluses looks terribly ugly and amateurish. Is it possible to do it somehow more efficiently using anything else? For example pattern? I dont know. Thanks for help :)
For simplicity, you can also do:
String.join(at, error,one, two, three, four);
You can use the java built-in StringBuilder
StringBuilder sb = new StringBuilder();
sb.append(error);
sb.append(at);
sb.append(one);
...
effect = sb.toString();
If the "#:" is a consistent separator, and you're using Java 8+, you might find that String.join is your friend. This would look something like:
effect = String.join("#:", error, one, two, three, four);
Guessing a little bit from your variable names, but as a little background and just in case it's helpful, if you want/need to use a Stream you can also use Collectors.joining, which could look something like:
List<String> stringParts = ...
stringParts.stream()
.collect(Collectors.joining("#:"));
This will join everything in the list with "#:" as a delimiter. You can also add a constant prefix and/or suffix which might be relevant for your error variable, like:
String error = RandomStringUtils.randomAlphabetic(3);
List<String> stringParts = ...
stringParts.stream()
.collect(Collectors.joining("#:", error, ""));
What's the simplest way of changing the w= number and h= number?
Example of url:
https://test.com/photos/226109/test-photo-226109.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb&fit=crop
I have to dynamically change bolded parts.
I can extract the value of w like this:
s = s.substring(s.indexOf("=") + 1, s.indexOf("&"));
But how could I change it?
I tried searching Stackoverflow, but couldn't find anything.
Thanks.
If i understood correctly you are trying to replace the values after the = sign for h and w.
You can simply do that with RegEx as follows:
"https://test.com/photos/226109/test-photo-226109.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb&fit=crop"
.replaceAll("w=\\d+", "w=NEW_VALUE").replaceAll("&h=\\d+", "&h=NEW_VALUE")
What is happening above is that we first find the patern that matches w=AnyNumberHere and we replace the entire section with w=NEW_VALUE. Likewise we replace &h=AnyNumberHere with &h=NEW_VALUE
This solution is not length depended, therefore if the URL has a variable length this will still work, and will even work if the value h=123 or w=1234 for example do not exist ;)
In your case you can use String replaceAll method. Example of use:
String string =
"https://test.com/photos/226109/test-photo-226109." +
"jpeg?w=1260&h=750&auto=compress&cs=tinysrgb&fit=crop";
String replacedString = string
.replaceAll(string.substring(string.indexOf("=") + 1,
string.indexOf("&")), "1000");
When you get your numbers from string you can convert it to StringBuffer.
Like this
String s = new String("https://test.com/photos/226109/test-photo-226109.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb&fit=crop");
StringBuffer sb = new StringBuffer(s);
sb.replace(s.indexOf("w=") + 2, s.indexOf("&"), "2000");
sb.replace(s.indexOf("h=") + 2, s.indexOf("&"), "2000");
s = sb.toString();
I have a string = ab:cd:ef:gh. On this input, I want to return the string ef:gh (third colon intact).
The string apple:orange:cat:dog should return cat:dog (there's always 4 items and 3 colons).
I could have a loop that counts colons and makes a string of characters after the second colon, but I was wondering if there exists some easier way to solve it.
You can use the split() method for your string.
String example = "ab:cd:ef:gh";
String[] parts = example.split(":");
System.out.println(parts[parts.length-2] + ":" + parts[parts.length-1]);
String example = "ab:cd:ef:gh";
String[] parts = example.split(":",3); // create at most 3 Array entries
System.out.println(parts[2]);
The split function might be what you're looking for here. Use the colon, like in the documentation as your delimiter. You can then obtain the last two indexes, like in an array.
Yes, there is easier way.
First, is by using method split from String class:
String txt= "ab:cd:ef:gh";
String[] arr = example.split(":");
System.out.println(arr[arr.length-2] + " " + arr[arr.length-1]);
and the second, is to use Matcher class.
Use overloaded version of lastIndexOf(), which takes the starting index as 2nd parameter:
str.substring(a.lastIndexOf(":", a.lastIndexOf(":") - 1) + 1)
Another solution would be using a Pattern to match your input, something like [^:]+:[^:]+$. Using a pattern would probably be easier to maintain as you can easily change it to handle for example other separators, without changing the rest of the method.
Using a pattern is also likely be more efficient than String.split() as the latter is also converting its parameter to a Pattern internally, but it does more than what you actually need.
This would give something like this:
String example = "ab:cd:ef:gh";
Pattern regex = Pattern.compile("[^:]+:[^:]+$");
final Matcher matcher = regex.matcher(example);
if (matcher.find()) {
// extract the matching group, which is what we are looking for
System.out.println(matcher.group()); // prints ef:gh
} else {
// handle invalid input
System.out.println("no match");
}
Note that you would typically extract regex as a reusable constant to avoid compiling the pattern every time. Using a constant would also make the pattern easier to change without looking at the actual code.
I have a string like this:
String str="\"myValue\".\"Folder\".\"FolderCentury\"";
Is it possible to split the above string by . but instead of getting three resulting strings only two like:
columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";
Or do I have to use an other java method to get it done?
Try this.
String s = "myValue.Folder.FolderCentury";
String[] a = s.split(java.util.regex.Pattern.quote("."));
Hi programmer/Yannish,
First of all the split(".") will not work and this will not return any result. I think java String split method not work for . delimiter, so please try java.util.regex.Pattern.quote(".") instead of split(".")
As I posted on the original Post (here), the next code:
String input = "myValue.Folder.FolderCentury";
String regex = "(?!(.+\\.))\\.";
String[] result=input.split(regex);
System.out.println("result: "+Arrays.toString(result));
Produces the required output (an array with two values):
result: [myValue.Folder, FolderCentury]
If the problem you're trying to solve is really that specific, you could do it even without using regular expression matches at all:
int lastDot = str.lastIndexOf(".");
columnArray[0] = str.substring(0, lastDot);
columnArray[1] = str.substring(lastDot + 1);