Replace String With Another in Java

How to replace part of a String in Java?

Use regex like this :

public static void main(String[] args) {
String s = "Hello my Dg6Us9k. I am alive";
String newString=s.replaceFirst("\\smy\\s\\w{7}", "");
System.out.println(newString);
}

O/P :
Hello. I am alive

Replace a char in a string with another string?

For your specific problem( replacing the first 'a'):

public String replaceFirst(String regex,
String replacement)

Replaces the first substring of this string that matches the given
regular expression with the given replacement.

That is:

String s="aaaaa";
String res=s.replaceFirst("a","bbbb");

For a general solution:

public StringBuilder replace(int start,
int end,
String str)

Parameters:

start - The beginning index, inclusive.

end - The ending index, exclusive.

str - String that will replace previous contents.

That is:

String s="aaaaa";
StringBuilder sb=new StringBuilder(s);
String res=sb.replace(0,1,"bbbb").toString();

Replace part of a string between indexes in Java

Firstly, you cannot do it1, since a String is immutable in java.

However, you can create a new String object with the desired value, using the String#substring() method (for example):

String s = "123456789";
String newString = s.substring(0, 3) + "foobar" + s.substring(3+3);
System.out.println(newString);

If you do want to achieve it efficiently, you could avoid creating some intermediate strings used by the concatinating and substring() method.

String s = "123456789";
StringBuilder sb = new StringBuilder();
char[] buff = s.toCharArray();
sb.append(buff , 0, 3).append("foobar");
sb.append(buff,3+3,buff.length -(3+3));
System.out.println(sb.toString());

However, if it is not done in a very tight loop - you should probably ignore it, and stick with the first and more readable solution.


(1) not easily anyway, it can be done with reflection - but it should be avoided.

replace String with another in java using regular Expression

You may use a constrained-width lookbehind solution like

public static String getMaskedValue(String value) {
return value.replaceAll("(?<=^.{0,6}).", "*");
}

See the Java demo online.

The (?<=^.{0,6}). pattern matches any char (but a line break char, with .) that is preceded with 0 to 6 chars at the start of the string.

A note on the use of lookbehinds in Java regexps:

✽ Java accepts quantifiers within lookbehind, as long as the length of
the matching strings falls within a pre-determined range. For
instance, (?<=cats?) is valid because it can only match strings of
three or four characters. Likewise, (?<=A{1,10}) is valid.

how to replace ' \' with '/' in a java string

replaceAll() needs Strings as parameters.
So, if you write

path = path.replaceAll('\', '/');

it fails because you should have written

path = path.replaceAll("\", "/");

But this also fails because character '\' should be typed '\\'.

path = path.replaceAll("\\", "/");

And this will fail during execution giving you a PatternSyntaxException, because the fisr String is a regular expression (Thanks @Bhavik Shah for pointing it out). So, writing it as a RegEx, as @jlordo gave in his answer:

path = path.replaceAll("\\\\", "/");

Is what you were looking for.

To make optimal your core, you should make it independent of the Operating System, so use @Thai Tran's tip:

path = path.replaceAll("\\\\", File.separator);

But this fails throwing an StringIndexOutOfBoundsException (I don't know why). It works if you use replace() with no regular expressions:

path = path.replace("\\", File.separator);

Android - how to replace part of a string by another string?

It is working, but it wont modify the caller object, but returning a new String.

So you just need to assign it to a new String variable, or to itself:

string = string.replace("to", "xyz");

or

String newString = string.replace("to", "xyz");

API Docs

public String replace (CharSequence target, CharSequence replacement) 

Since: API Level 1

Copies this string replacing
occurrences of the specified target
sequence with another sequence. The
string is processed from the beginning
to the end.

Parameters

  • target the sequence to replace.
  • replacement the replacement
    sequence.

Returns the resulting string.

Throws NullPointerException if target or replacement is null.

Replace string values from any Object class - Java

Modify the value according to your requirements (See https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#replaceAll(java.lang.String,java.lang.String))

And then set the changed value onto the object.

        if (value instanceof java.lang.String) {
String newValue = ((String)value).replace(regex, replacement);
field.set(obj, newValue);

}

Your case may be different, but in many cases if you're having to use reflection, you may be missing a simpler way to do things.



Related Topics



Leave a reply



Submit