You can use replaceFirst(String regex, String replacement) method of String.
You can use replaceFirst(String regex, String replacement) method of String.
You should use already tested and well documented libraries in favor of writing your own code.
org.apache.commons.lang3.
StringUtils.replaceOnce("coast-to-coast", "coast", "") = "-to-coast"
Javadoc
- https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#replaceOnce-java.lang.String-java.lang.String-java.lang.String-
There's even a version that is case insensitive (which is good).
Maven
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
Credits
My answer is an augmentation of: https://stackoverflow.com/a/10861856/714112
String.replaceFirst will do the job.
String output = input.replaceFirst("s","");
String.replaceFirst is heavyweight
public String replaceFirst(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}
this is the fastest way
str = str.substring(0, 4) + s.substring(5);
StringBuilder would be my first idea, as has already been demonstraed, a char array might be an idea, but String already has this functionality built in String#replaceFirst, for example
public static String changeFirst(String in, char old, char with) {
String oldValue = Pattern.quote(Character.toString(old));
String withValue = Matcher.quoteReplacement(Character.toString(with));
return in.replaceFirst(oldValue, withValue);
}
Then you could use it something like...
String replaced = changeFirst("Banana's with Pajamas", 'P', 'K');
System.out.println(replaced);
replaced = changeFirst("Apples", 'P', 'K');
System.out.println(replaced);
replaced = changeFirst("What's with the *uck", '*', 't');
System.out.println(replaced);
Which outputs something like...
Banana's with Kajamas
Apples
What's with the tuck
You should show us what you have done unto this point however I am providing a hint here. Note since it is homework I will Not just give you the answer
public static String changeFirst(String s, char oldChar, char newChar){
//now how to implement it
//play around with methods like this
s.indexOf(oldChar);//this gets you the leftmost occurence
//and
//string+char or string+ string or char+char creates a sttring
//and try "someString".substring(a,b);// creates a substring from a inclusive to //be exclusive (0 is the first character.) so "foo".substring(0,2).equals("fo") //f is the 0th character o is the first and the second oh is the 2th character //but isnt counted
//next time put some effort into the questions you ask here let us know all the information and the issues you had
}