Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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.

share|improve this question
1  
Why do you replace 'Is' to 'It' if you only need to replace the 1st 's' or 'S' in each work ? Can you correct the layout and give one or more clear example ? – Benoit Vanalderweireldt 4 hours ago
1  
Got it the first occurence of each 's' or 'S' – Benoit Vanalderweireldt 4 hours ago
    
@Hedgebox I hope you have got your answer. But have provided a different approach to solve your problem. See my answer. – mmuzahid 3 hours ago

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.
share|improve this answer
1  
@im-biegeleisen your solution is perfect with some adjustments. Check my post – Thush-Fdo 3 hours ago
1  
This gets the wrong result for a word like "Systems" with a capital "S" and lower case "s" (at least as I understood the question). – msandiford 3 hours ago
    
Systems -> Tyttems ... what is the problem? – Tim Biegeleisen 3 hours ago
    
@Tim Biegeleisen : msandiford seems to be correct... I just tried it...I would want "Systems" to become "Tystems"... only the 1st occurance of either "S" or "s" to "T" or "t" – Hedgebox 2 hours ago
    
@Hedgebox I updated my answer per your requirements. – Tim Biegeleisen 2 hours ago

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 smallS = parts[i].indexOf("s");
    int capS = parts[i].indexOf("S");

    if (smallS != -1 && (capS == -1 || smallS < capS))
        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. 
share|improve this answer
    
@cricket_007 is it OK now? – mmuzahid 3 hours ago
    
@cricket_007 edited by going to different approach :) – mmuzahid 3 hours ago
    
ASCII shifting... It'll work, but it is very specific to this one problem – cricket_007 3 hours ago
    
@cricket_007 yes.... but I hope this will provide a faster solution than other answer. – mmuzahid 3 hours ago
    
@mmuzahid: tks for your solution but I am trying to get a better understanding of the uses of replaceFirst...without the use of StringBuilder at this point. – Hedgebox 2 hours ago

Use below amendment to Tim Biegeleisen's answer (before editing his post)

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

for (String part : parts) {
    sb.append(part.replaceFirst("s", "t").replaceFirst("S", "T"));
    sb.append(" ");
}

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

Edit - You can use concat()

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

String output = "";

for (String part : parts) {
    output = output.concat(part.replaceFirst("s", "t").replaceFirst("S", "T") + " ");
}

    System.out.println(output);

Update

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

    String output = "";

    for (String part : parts) {
        output = output.concat(part.replaceFirst("s", "t") + " ");
    }

    String[] parts2 = input.split(" ");

    output = "";

    for (String part : parts2) {
        output = output.concat(part.replaceFirst("S", "T") + " ");
    }
    System.out.println(output);
share|improve this answer
1  
I do want to use String methods...is there a way to do it without using StringBuilder? – Hedgebox 3 hours ago
1  
@hedgebox : check edit part – Thush-Fdo 3 hours ago
1  
Perfect many tks. – Hedgebox 3 hours ago
2  
@Hedgebox FYI StringBuilder provides better performance than + – mmuzahid 3 hours ago
    
@Thush-Fdo: msandiford in his comment below...seems to be correct... I just tried it...I would want "Systems" to become "Tystems"... only the 1st occurance of either "S" or "s" to "T" or "t". When I changes "systems" to "Systems" the code produced "Tyttems" not "Tystems". – Hedgebox 2 hours ago

My method would be less dependent on those string methods you've mentioned.

String phrase;
String [] parts = phrase.split(" ");

for (int i = 0; i < parts.length; i++ ) {
    for (int j = 0; j < parts[i].length(); j++) {
        if (parts[i].charAt(j) == 's') {
            parts[i] = "t" + parts[i].substring(1);
            break;
        } else if (parts[i].charAt(0) == 'S') {
            parts[i] = "T" + parts[i].substring(1);
            break;
        }
    }
}

String modifiedPhrase = "";

for (int i = 0; i < parts.length; i++ ) {
    modifiedPhrase += parts[i] + " ";
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.