1

How would I replace a string 10100 with 10010 using the algorithm "replace the last substring 10 with 01." I tried

s=s.replace(s.substring(a,a+2), "01");

but this returns 01010, replacing both the first and the second substring of "10". "a" represents s.lastindexOf("10");

user1569897
  • 437
  • 1
  • 5
  • 12

5 Answers5

3

Here's a simple and extensible function you can use. First its use/output and then its code.

String original  = "10100";
String toFind    = "10";
String toReplace = "01";
int ocurrence    = 2;
String replaced  = replaceNthOcurrence(original, toFind, toReplace, ocurrence);
System.out.println(replaced); // Output: "10010"

original  = "This and This and This";
toFind    = "This";
toReplace = "That";
ocurrence = 3;
replaced  = replaceNthOcurrence(original, toFind, toReplace, ocurrence);
System.out.println(replaced); // Output: "This and This and That"

Function code:

public static String replaceNthOcurrence(String str, String toFind, String toReplace, int ocurrence) {
    Pattern p = Pattern.compile(Pattern.quote(toFind));
    Matcher m = p.matcher(str);
    StringBuffer sb = new StringBuffer(str);
    int i = 0;
    while (m.find()) {
        if (++i == ocurrence) { sb.replace(m.start(), m.end(), toReplace); break; }
    }
    return sb.toString();
}
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
1

If you want to access the last two indices of a string, then you can use: -

str.substring(str.length() - 2);

This gives you string from index str.length() - 2 to the last character, which is exactly the last two character.

Now, you can replace the last two indices with whatever string you want.

UPDATE: -

Of you want to access the last occurrence of a character or substring, you can use String#lastIndexOf method: -

str.lastIndexOf("10");

Ok, you can try this code: -

String str = "10100";
int fromIndex = str.lastIndexOf("10");
str = str.substring(0, fromIndex) + "01" + str.substring(fromIndex + 2);
System.out.println(str);
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • its not exactly the last two indices, but the last occuring example of 10, accessable using lastINdexOf – user1569897 Oct 26 '12 at 18:32
  • i understand, i know how to get the particular substring, but I can't replace that substring at that index without replacing all other substrings that match that are at other indexes – user1569897 Oct 26 '12 at 18:36
  • @user1569897. Take a look at both the code I posted. You can use either of them. – Rohit Jain Oct 26 '12 at 18:43
  • @Rohit - Your first solution is not correct; it still replaces all occurances of "10" with "01" – Jim Oct 26 '12 at 18:57
  • @Jim. Ah! Sorry. Didn't notice that. Got lost in 0's and 1's. Thanks for pointing :) – Rohit Jain Oct 26 '12 at 19:00
0

You can get the last index of a character or substring using string's lastIndexOf method. See the documentation link below for how to use it.

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#lastIndexOf(java.lang.String)

Once you know the index of your substring, you can get the substring of all characters before that index, and the substring of all characters after the last character in your search string, and concatenate.

This is a little drawn out, and I didn't actually run it (so I might have a syntax error), but it gives you the point of what I'm trying to convey at least. You could do this all in one line if you want, but it wouldn't illustrate the point as well.

string s = "10100";
string searchString = "10";
string replacementString = "01";
string charsBeforeSearchString = s.substring(0, s.lastIndexOf(searchString) - 1);
string charsAfterSearchString = s.substring(s.lastIndexIf(searchString) + 2);
s = charsBeforeSearchString + replacementString + charsAfterSearchString;
Jim
  • 6,753
  • 12
  • 44
  • 72
  • Is there a way to just replace that index without concatenating? – user1569897 Oct 26 '12 at 18:37
  • I don't see why you want to avoid concatenating. String has a replaceFirst method, but no replaceLast; so you could replace the first occurrance without manually concatenating (although it will concatenate behind the scenes anyways), but not the last. – Jim Oct 26 '12 at 18:41
  • Well, once you know the lastIndexOf your search string, you could convert the string to a char array and replace individual characters, without doing any string concatenation. Don't know why you would choose to do that instead of just grabbing out the substrings before and after your last "10", and concate them back together with a "01" inbetween. – Jim Oct 26 '12 at 18:44
  • Your suggested solution that uses Replace instead of manually concatenating wouldn't work because you would still replace all occurances of "10" with "01". With that said, sure you can do it without manually concatenating strings, and instead use Replace, but why? What's the benefit? It's less clear code. – Jim Oct 26 '12 at 18:56
0

10100 with 10010

String result = "10100".substring(0, 2) + "10010".substring(2, 4) + "10100".substring(4, 5);
0

The easiest way:

String input = "10100";
String result = Pattern.compile("(10)(?!.*10.*)").matcher(input).replaceAll("01");
System.out.println(result);
elias
  • 15,010
  • 4
  • 40
  • 65