Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String ReplaceFirst

I am reading in a string

Is Mississippi a State where there are many systems.

I would like to replace the 1st "s" or "S" in each word with "t" or "T" (i.e keeping the same case)...so that the output is:

It Mitsissippi a Ttate where there are many tystems.

I have tried

s= s.replaceFirst("(?i)S", "t"); [which of course didn't work]

and have experimented trying to split the string using a string [] .split(Pattern.quote("\\s")) then trying to figure out how to replaceFirst() each element of the array and then return the values back to a string [but couldn't figure out the right way of doing it].

I thought \\G might help to restart at the next word but have gotten no where. Any help using these 3 methods is appreciated.

like image 501
Hedgebox Avatar asked Mar 31 '16 04:03

Hedgebox


People also ask

What does string replaceFirst do in Java?

The replaceFirst() method returns a new string where the first occurrence of the matching substring is replaced with the replacement string.

How do you replace only one occurrence of a string in Java?

To replace the first occurrence of a character in Java, use the replaceFirst() method.

How do I change the first letter of a string in Java?

The Java String replaceFirst() method replaces the first substring 'regex' found that matches the given argument substring (or regular expression) with the given replacement substring. The substring matching process start from beginning of the string (index 0).


2 Answers

One option would be to split the string into words, and then use String.replaceFirst() on each word to replace the first occurrence of s with t (or any other letter you want):

Update:

I refactored my solution to find the first occurrence of any s (upper or lower case), and to apply the appropriate conversion on it.

String input = "Is Mississippi a State where there are many systems.";
String[] parts = input.split(" ");
StringBuilder sb = new StringBuilder("");

for (int i=0; i < parts.length; ++i) {
    if (i > 0) {
        sb.append(" ");
    }
    int index = parts[i].toLowerCase().indexOf('s');
    if (index >= 0 && parts[i].charAt(index) == 's') {
        sb.append(parts[i].replaceFirst("s", "t"));
    }
    else {
        sb.append(parts[i].replaceFirst("S", "T"));
    }
}

System.out.println(sb.toString());

Output:

It Mitsissippi a Ttate where there are many tystems.
like image 53
Tim Biegeleisen Avatar answered Nov 15 '22 22:11

Tim Biegeleisen


Approach-1: Without using replace and split method for better performance.

String str = "Is Mississippi a State where there are many systems.";
System.out.println(str);

char[] cArray = str.toCharArray();
boolean isFirstS = true;
for (int i = 0; i < cArray.length; i++) {
    if ((cArray[i] == 's' || cArray[i] == 'S') && isFirstS) {
        cArray[i] = (cArray[i] == 's' ? 't' : 'T');
        isFirstS = false;
    } else if (Character.isWhitespace(cArray[i])) {
        isFirstS = true;
    }
}
str = new String(cArray);

System.out.println(str);

EDIT: Approach2: As you need to use replaceFirst method and you dont want to use StringBuilder here is an option for you:

String input = "Is Mississippi a State where there are many Systems.";
String[] parts = input.split(" ");
String output = "";

 for (int i = 0; i < parts.length; ++i) {
     int smallSIndx = parts[i].indexOf("s");
     int capSIndx = parts[i].indexOf("S");

     if (smallSIndx != -1 && (capSIndx == -1 || smallSIndx < capSIndx))
         output += parts[i].replaceFirst("s", "t") + " ";
     else
         output += parts[i].replaceFirst("S", "T") + " ";
 }

System.out.println(output); //It Mitsissippi a Ttate where there are many Tystems. 

Note: I prefer approach 1 because it has no overhead for the method replaceFisrt and split , String append or concat

like image 23
mmuzahid Avatar answered Nov 15 '22 22:11

mmuzahid