简体   繁体   中英

how can I write a function string replace (char a , char b, string s) that replace each occurrence of the character a in the string s by b

i tried in following steps. But I don't know what should I do next.Only use s.equals(""),s.charAt(0),s.substring(1) .Others way are NOT allowed.

public string remove1 (char c, string s){
string to_ret = "";
while(true){
   if (s.equals("")) return to_ret;
   char c2 = s.charAt(0);
   if (c2 = c) return to_ret+s.substring(1)
   to_ret = to _ret;
   s = s.substring(1);
}

remove("e","hello")

What can I do next?

如果我了解您的问题,您可以按照以下步骤进行操作:

s = s.replace('a', 'b');
public String remove(char a, char b, String s) {
    String retString = "";
    for (int i = 0; i < s.length(); i++) {
        char stringChar = s.charAt(i);
        if (stringChar == a) {
            retString = retString + b;
        } else {
            retString = retString + stringChar;
        }
    }
    return retString;
}

Let me introduce you one recursion:

public String replace(char a, char b, String s) {
    if (s.equals("") return "";
    char ch = s.charAt(i);
    if (stringChar == a) {
        return b+ replace(a,b,s.substring(1))
    } else {
        return ch+ replace(a,b,s.substring(1))
    }   
}

Is this a homework question?

public String remove1 (char c,char b, String s){
String to_ret = "";
int len = s.length();
for(int i =0 ; i< len ; i++){
    if (s.equals("")) return to_ret;
    char c2 = s.charAt(i);
    if (c2 == c) 
        to_ret = to_ret + b;
    else
        to_ret = to_ret + c2; 

}
return to_ret;
}

It would appear someone is trying to teach you functional programming principles in Java. I'd question the choice of language for that. Even so, you should look toward recursion for your solution. Thing of the String as a list of characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM