Replacing all subsequent characters of a string, after matching a substring - java

I try to replace a character and all it's following characters within a string with another character.
This is my code so far.
String name = "Peter Pan";
name = name.replace("er", "abc");
Log.d("Name", name)
the result should be: "Petabc"
I would highly appreciate any help on this matter!

A way to achive your goal:
search the string for the first appearance of the sequnce you want to replace
use that index and cut the string using String#substring
add your replace sequence to the end of the substring you just created
fin.
Good luck.
EDIT
In code it might look like this (not tested)
public static String customReplace(String input, String replace)
{
int index = input.indexOf(replace);
if(index >= 0)
{
return input.substring(index) + replace; //cutting string down to the required part and adding the replace
}
else
return null; //String 'input' doesn't contain String 'replace'
}

You could use a Regular Expression here with String's built-in replaceAll method to very easily do what you want:
original.replaceFirst(toReplace + ".*", replaceWith);
For example:
String original = "testing 123";
String toReplace = "ing";
String replaceWith = "er";
String replaced = original.replaceFirst(toReplace + ".*", replaceWith);
After the above, replaced will be set to "tester".

Related

How to put new string between commas in original string

I have this original string and I want to insert new string between two dots of original string. I did it this way, but having errors.
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String new = originalString.replace(originalString.substring(originalString.indexOf(".") + 1), stringForReplace);
it gives me: "asdASfasdlpe.NewString"
Result should be: "asdASfasdlpe.NewString.asdasfdfepw"
I would do it like so.
from the question it looks like you want to replace the first occurrence so use replaceFirst
(?<=\\.) - look behind assertion - so start with following character
(?=\\.) - look ahead assertion - so end prior to that
.*? - reluctant quantifier to limit to just characters between two periods. Use * in case you have two adjacent periods since the string could be empty.
String s = "first.oldstring.third.fourth.fifth";
String n = "second";
s = s.replaceFirst("(?<=\\.).*?(?=\\.)",n);
System.out.println(s);
prints
first.second.third.fourth.fifth
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String a[]=originalString.split("[.]");
String newString="";
if(a.length==3) {
newString=originalString.replace(a[1], stringForReplace);
}
System.out.println(newString);
Or with ternary operator:
newString=(a.length== 3 ? originalString.replace(a[1], stringForReplace):null);
System.out.println(newString);
One shorter solution is to use regex with a lookahead and lookbehind
String replaced = originalString.replaceAll("(?<=\\.).+(?=\\.)", stringForReplace);
The problem with your code is due to using this particular piece of code:
originalString.substring(originalString.indexOf(".") + 1)
The reason is that indexof() function will only give the index on which "." was found on, and substring will only know where to start taking the substring from, but it wouldn't know where to end it.
Try this:
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String newString = originalString.replace(originalString.split("[.]", 3)[1], stringForReplace);
System.out.println(newString);
The split function in this piece of code will break the whole string by "."
and you will have the string you want to replace available to you.
originalString.split("[.]", 3)[1]
You could try the following:
public static void main(String[] args) {
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String newStr = originalString.replaceAll("(?<=\\.).*(?=\\.)", stringForReplace);
//using lookahead and lookbehind regex
String newStr2 = originalString.replaceAll("\\..*\\.", "."+stringForReplace+".");
System.out.println(newStr);
System.out.println(newStr2);
}
One option uses lookahead and lookbehinds, you could opt to not use that if it is not supported.
Output:
asdASfasdlpe.NewString.asdasfdfepw
asdASfasdlpe.NewString.asdasfdfepw
Here You go:
String new = originalString.replace(originalString.substring(originalString.indexOf(".") + 1), stringForReplace)+originalString.substring(originalString.indexOf(".",originalString.indexOf(".")+1),originalString.length());
What I have done is adding the resultant string to the new String.indexOf function takes another argument too, which is the position the search will start

String replace according to position?

I have this String 11101011.I want to replace last three char '011' with 101.is there any function of String in java to do so?
Use string.replaceAll function.
string.replaceAll(".{3}$", "101");
.{3} matches exactly three characters and $ asserts that the match must be followed by an end of the line.
Example:
String name = "11101011";
String result = name.replaceAll(".{3}$", "101");
System.out.println(result);
Output:
11101101
Using String replace and regular expressions for this task seems like breaking butterflies on a wheel - just cut the last three characters off and append the new suffix (ultimately verbose solution):
final String oldString = "11101011";
final String oldSuffix = oldString.substring(5);
final String reducedOldString = oldString.substring(0, oldString.length() - oldSuffix.length());
final String newSuffix = "101";
final String newString = reducedOldString.concat(newSuffix);
System.out.println("newString = " + newString);
Use replace method of String class
String s="11101011";
System.out.println(s.replace("011","101"));
O/P:
11101101

How to replace part of a String in Java?

Im trying to replace part of a String based on a certain phrase being present within it. Consider the string "Hello my Dg6Us9k. I am alive.".
I want to search for the phase "my" and remove 8 characters to the right, which removes the hash code. This gives the string "Hello. I am alive." How can i do this in Java?
You could achieve this through string.replaceAll function.
string.replaceAll("\\bmy.{8}", "");
Add \\b if necessary. \\b called word boundary which matches between a word character and a non-word character. .{8} matches exactly the following 8 characters.
To remove also the space before my
System.out.println("Hello my Dg6Us9k. I am alive.".replaceAll("\\smy.{8}", ""));
This should do it:
String s = ("Hello my Dg6Us9k. I am alive");
s.replace(s.substring(s.indexOf("my"), s.indexOf("my")+11),"");
That is replacing the string starts at "my" and is 11 char long with nothing.
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
Java strings are immutable, so you cannot change the string. You have to create a new string. So, find the index i of "my". Then concatenate the substring before (0...i) and after (i+8...).
int i = s.indexOf("my");
if (i == -1) { /* no "my" in there! */ }
string ret = s.substring(0,i);
ret.concat(s.substring(i+2+8));
return ret;
If you want to be flexible about the hash code length, use the folowing regexp:
String foo="Hello my Dg6Us9k. I am alive.";
String bar = foo.replaceFirst("\\smy.*?\\.", ".");
System.out.println(bar);

How to replace all numbers in java string

I have string like this String s="ram123",d="ram varma656887"
I want string like ram and ram varma so how to seperate string from combined string
I am trying using regex but it is not working
PersonName.setText(cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(1))).replaceAll("[^0-9]+"));
The correct RegEx for selecting all numbers would be just [0-9], you can skip the +, since you use replaceAll.
However, your usage of replaceAll is wrong, it's defined as follows: replaceAll(String regex, String replacement). The correct code in your example would be: replaceAll("[0-9]", "").
You can use the following regex: \d for representing numbers. In the regex that you use, you have a ^ which will check for any characters other than the charset 0-9
String s="ram123";
System.out.println(s);
/* You don't need the + because you are using the replaceAll method */
s = s.replaceAll("\\d", ""); // or you can also use [0-9]
System.out.println(s);
To remove the numbers, following code will do the trick.
stringname.replaceAll("[0-9]","");
Please do as follows
String name = "ram varma656887";
name = name.replaceAll("[0-9]","");
System.out.println(name);//ram varma
alternatively you can do as
String name = "ram varma656887";
name = name.replaceAll("\\d","");
System.out.println(name);//ram varma
also something like given will work for you
String given = "ram varma656887";
String[] arr = given.split("\\d");
String data = new String();
for(String x : arr){
data = data+x;
}
System.out.println(data);//ram varma
i think you missed the second argument of replace all. You need to put a empty string as argument 2 instead of actually leaving it empty.
try
replaceAll(<your regexp>,"")
you can use Java - String replaceAll() Method.
This method replaces each substring of this string that matches the given regular expression with the given replacement.
Here is the syntax of this method:
public String replaceAll(String regex, String replacement)
Here is the detail of parameters:
regex -- the regular expression to which this string is to be matched.
replacement -- the string which would replace found expression.
Return Value:
This method returns the resulting String.
for your question use this
String s = "ram123", d = "ram varma656887";
System.out.println("s" + s.replaceAll("[0-9]", ""));
System.out.println("d" + d.replaceAll("[0-9]", ""));

How to get specific string out of long string

I have the following String (it is variable, but classpath is always the same):
C:.Users.mho.Desktop.Eclipse.workspace.GIT.BLUBB...bin.de.test.class.mho.communication.InterfaceXmlHandler
and I want to get just
de.test.class.mho.communication.InterfaceXmlHandler
out of this string. The end
InterfaceXmlHandler
is variable, also the beginning before 'de' and the path itself is variable too, but
de.test.class.mho.
isn't variable.
Why not just use
String result = str.substring(str.lastIndexOf("de.test.class.mho."));
Instead of splitting you could get rid of the beginning of the string:
String input = "C:.Users.mho.Desktop.Eclipse.workspace.GIT.BLUBB...bin.de.test.class.mho.communication.InterfaceXmlHandler";
String output = input.replaceAll(".*(de\\.test\\.class\\.mho.*)", "$1");
You can create a string-array with String.split("de.test.class.mho."). The Array will contain two Strings, the second String will be what you want.
String longString = ""; //whatever
String[] urlArr = longString.split("de.test.class.mho.");
String result;
if(urlArr.length > 1) {
result = "de.test.class.mho." urlArr[1]; //de.test.class.mho.whatever.whatever.whatever
}
You can use replaceAll() to "extract" the part you want:
String part = str.replaceAll(".*(?=de\\.test\\.class\\.mho\\.)", "");
This uses a look-ahead to find all characters before the target, and replace them with a blank (ie delete them).
You could quite reasonably ignore escaping the dots for brevity:
String part = str.replaceAll(".*(?=de.test.class.mho.)", "");
I doubt it would give a different result.

Categories