Java replaceALL for string - java

I have a string:
100-200-300-400
i want replace the dash to "," and add single quote so it become:
'100','200','300','400'
My current code only able to replace "-" to "," ,How can i plus the single quote?
String str1 = "100-200-300-400";
split = str1 .replaceAll("-", ",");
if (split.endsWith(","))
{
split = split.substring(0, split.length()-1);
}

You can use
split = str1 .replaceAll("-", "','");
split = "'" + split + "'";

As an alternative if you are using java 1.8 then you could create a StringJoiner and split the String by -. This would be a bit less time efficient, but it would be more safe if you take, for example, a traling - into account.
A small sample could look like this.
String string = "100-200-300-400-";
String[] splittet = string.split("-");
StringJoiner joiner = new StringJoiner("','", "'", "'");
for(String s : splittet) {
joiner.add(s);
}
System.out.println(joiner);

This will work for you :
public static void main(String[] args) throws Exception {
String s = "100-200-300-400";
System.out.println(s.replaceAll("(\\d+)(-|$)", "'$1',").replaceAll(",$", ""));
}
O/P :
'100','200','300','400'
Or (if you don't want to use replaceAll() twice.
public static void main(String[] args) throws Exception {
String s = "100-200-300-400";
s = s.replaceAll("(\\d+)(-|$)", "'$1',");
System.out.println(s.substring(0, s.length()-1));
}

Related

Unwanted elements appearing when splitting a string with multiple separators in Java

I have a string from which I need to remove all mentioned punctuations and spaces. My code looks as follows:
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s+]");
System.out.println("spart[0]: " + spart[0]);
System.out.println("spart[1]: " + spart[1]);
System.out.println("spart[2]: " + spart[2]);
System.out.println("spart[3]: " + spart[3]);
System.out.println("spart[4]: " + spart[4]);
But, I am getting some elements which are blank. The output is:
spart[0]: s
spart[1]: film
spart[2]:
spart[3]: fever
spart[4]: normal
My desired output is:
spart[0]: s
spart[1]: film
spart[2]: fever
spart[3]: normal
spart[4]: curse
Try with this:
public static void main(String[] args) {
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s]+");
for (String string : spart) {
System.out.println("'"+string+"'");
}
}
output:
's'
'film'
'fever'
'normal'
'curse'
I believe it is because you have a Greedy quantifier for space at the end there. I think you would have to use an escape sequence for the plus sign too.
String spart = s.replaceAll( "\\W", " " ).split(" +");

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);
}

Remove all words starting with "http" in a string?

I simply want to replace all words starting with "http" and ends with space or "\n" in a string
Example string is.
Full results below;
http://www.google.com/abc.jpg is a url of an image.
or some time it comes like https://www.youtube.com/watch?v=9Xwhatever this is an example text
Result of the string should be like
is a url of an image.
or some time it comes like this is an example text
I simply want to replace it with ""; i know the logic but don't know the function.
My logic is
string.startwith("http","\n")// starts with http and ends on next line or space
.replaceAll("")
public static void main(String[] args) {
String s = "https://www.google.com/abc.jpg is a url of an image.";
System.out.println(s.replaceAll("https?://.*?\\s+", ""));
}
O/P :
is a url of an image.
String.replaceAll() allows you to use a regex. In a regex, ^ allows you to capture the beginning of the String. Hence, you can do like that :
System.out.print("http://google-http".replaceAll("^http", ""));
result:
://google-http
The http at the beginning has be removed but not the one at the end.
public static void main(String[] args) {
String str = "https://www.google.com/abc.jpg is a url of an image.";
String subStr1 = "http://";
String substr2 = "https://";
String foundStr = "";
if(str.startsWith(subStr1)) {
foundStr = subStr1;
}
if (str.startsWith(subStr2)) {
foundStr = subStr2;
}
str = str.replaceAll(foundStr, "");
str = str.replaceAll(" ", "");
}

How to use replaceFirst to Replace {....}

I am having a string which contains xyaahhfhajfahj{adhadh}fsfhgs{sfsf}.
Now I want to replace {string} with a space.
I want to replace the curly brackets and the string in it with null.
I want to use replaceFirst for it but I don't know the regex for doing it.
Try this:
public class TestCls {
public static void main(String[] args) {
String str = "xyaahhfhajfahj{adhadh}fsfhgs{sfsf}";
String str1 = str.replaceAll("\\{[a-zA-z0-9]*\\}", " ");// to replace string within "{" & "}" with " ".
String str2 = str.replaceFirst("\\{[a-zA-z0-9]*\\}", " ");// to replace first string within "{" & "}" with " ".
System.out.println(str1);
System.out.println(str2);
}
}
If you're saying that you want to find the first occurrence of anything inside of { and }, then replace it including the brackets with nothing, here's an example that will do that:
String input = "xyaahhfhajfahj{adhadh}fsfhgs{sfsf}";
String output = input.replaceFirst("\\{.*?\\}", "");
System.out.println(output ); // output will be "xyaahhfhajfahjfsfhgs{sfsf}"

removing space before new line in java

i have a space before a new line in a string and cant remove it (in java).
I have tried the following but nothing works:
strToFix = strToFix.trim();
strToFix = strToFix.replace(" \n", "");
strToFix = strToFix.replaceAll("\\s\\n", "");
myString.replaceAll("[ \t]+(\r\n?|\n)", "$1");
replaceAll takes a regular expression as an argument. The [ \t] matches one or more spaces or tabs. The (\r\n?|\n) matches a newline and puts the result in $1.
try this:
strToFix = strToFix.replaceAll(" \\n", "\n");
'\' is a special character in regex, you need to escape it use '\'.
I believe with this one you should try this instead:
strToFix = strToFix.replace(" \\n", "\n");
Edit:
I forgot the escape in my original answer. James.Xu in his answer reminded me.
Are you sure?
String s1 = "hi ";
System.out.println("|" + s1.trim() + "|");
String s2 = "hi \n";
System.out.println("|" + s2.trim() + "|");
prints
|hi|
|hi|
are you sure it is a space what you're trying to remove? You should print string bytes and see if the first byte's value is actually a 32 (decimal) or 20 (hexadecimal).
trim() seems to do what your asking on my system. Here's the code I used, maybe you want to try it on your system:
public class so5488527 {
public static void main(String [] args)
{
String testString1 = "abc \n";
String testString2 = "def \n";
String testString3 = "ghi \n";
String testString4 = "jkl \n";
testString3 = testString3.trim();
System.out.println(testString1);
System.out.println(testString2.trim());
System.out.println(testString3);
System.out.println(testString4.trim());
}
}

Categories