如何用String中的新字符替换特定字符的第一个匹配项?

时间:2016-01-03 02:57:29

标签: java methods

我正在写一个签名为:

的方法
itertools.islice

该方法应该返回一个字符串,其中s中最左边的oldChar被newChar替换。如果oldChar没有出现在s中,该方法应该只返回s.Help?

2 个答案:

答案 0 :(得分:1)

你应该告诉我们你在这一点上所做的事情,但我在这里提供一个提示。请注意,因为它是家庭作业我不会只给你答案

    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
    }

答案 1 :(得分:1)

StringBuilder将是我的第一个想法,正如已经证明的那样,char数组可能是一个想法,但String已经在String#replaceFirst内置了此功能,例如

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);
}

然后你就可以使用它......

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);

其中输出类似......

Banana's with Kajamas
Apples
What's with the tuck