简体   繁体   English

如何在不使用.replace的情况下替换Java中字符串中的字符?

[英]How to replace characters in a string in Java without using .replace?

The goal of this program is to prompt the user for a single character and a phrase, and then replace any instances of that character within that phrase with a '$'. 此程序的目标是提示用户输入单个字符和短语,然后用'$'替换该短语中该字符的任何实例。 My program below does just that, but when I showed it to my professor I was told that I cannot use .replace in the methods I built, so I have to figure out a way to not use that. 我的程序就是这样做的,但是当我向我的教授展示时,我被告知我不能在我构建的方法中使用.replace,所以我必须找到一种不使用它的方法。 I have worked at it for a while, and thus far I know that I can replace it with a for loop, but after several frustrating iterations, I can't seem to get it right. 我已经工作了一段时间,到目前为止我知道我可以用for循环替换它,但经过几次令人沮丧的迭代之后,我似乎无法做到正确。 Excuse me if my code looks funky, I am still an introductory java student so I'm still learning the basics. 对不起,如果我的代码看起来很时髦,我仍然是一名入门的java学生,所以我还在学习基础知识。 I have provided a proposed solution at the end of my code snippet below. 我在下面的代码片段末尾提供了一个建议的解决方案。

public static char getKeyCharacter(String userInput) {

    char keyCharacter;
    Scanner inputStream = new Scanner(System.in);
    while(userInput.length() > 1) 
    {
        System.out.println("Please enter a SINGLE character to use as key: ");
        userInput = inputStream.nextLine();
    }
    keyCharacter = userInput.charAt(0);

    return keyCharacter;
}
public static String getString(String userResponse) {

    Scanner inputStream = new Scanner(System.in);
    String theString;
    while(userResponse.length() > 500) {
        System.out.println("Please enter a phrase or sentence >= 4 and <=500 characters: ");
        userResponse = inputStream.nextLine();
    }
    while(userResponse.length() < 4) {
        System.out.println("Please enter a phrase or sentence >= 4 and <=500 characters: ");
        userResponse = inputStream.nextLine();

    }

    theString = userResponse;
    return theString;

}
public static String maskCharacter(String theString, char keyCharacter){

    String maskedString = "";
    final char mask = '$';
    maskedString = maskedString + theString.replace(keyCharacter, mask);
    System.out.println("String with " + keyCharacter + " masked: ");
    return maskedString;
}

public static String removeCharacter(String theString, char keyCharacter) {

    String modifiedString = " ";
    final char replaceChar = ' ';
    modifiedString = modifiedString + theString.replace(keyCharacter, replaceChar);
    System.out.println("String with " + keyCharacter + " removed:");
    return modifiedString;

}

public static int countKey(String theString, char keyCharacter) {
    int charCount = 0;
    for (int c = 0; c < theString.length(); c++) {
        if (theString.charAt(c) == keyCharacter) {
            charCount++;
        }
    }
    System.out.println("Occurences of " + keyCharacter + " in string:");
    return charCount;
}  

} }

I believe the solution is will look something like this, but thus far I've been unsuccesful - 我相信解决方案看起来会像这样,但到目前为止我一直不成功 -

public static String maskCharacter(String theString, char keyCharacter){

    String maskedString = "";
    final char mask = '$';
    for (int k = 0; k < theString.length(); k++) {
        if (theString.charAt(k) == keyCharacter) {
            keyCharacter = mask;
         }
    System.out.println("String with " + keyCharacter + " masked: ");
    return maskedString;
}

My issue lies in making the maskedString = theString with all the keyCharacters replaced by mask. 我的问题在于使用mask替换所有keyCharacters,使maskedString = theString。 For the record, I have yet to learn anything about those fancy arrays, so if there is a way to do this using a simple for loop I would greatly appreciate it. 为了记录,我还没有学习任何关于那些花哨的数组,所以如果有一种方法可以使用一个简单的for循环来做到这一点我会非常感激。 Thank you for the assistance in advance! 感谢您的帮助!

I would use a StringBuilder and String#toCharArray() with a simple for-each loop. 我会使用StringBuilderString#toCharArray()以及一个简单的for-each循环。 Like, 喜欢,

public static String maskCharacter(String theString, char keyCharacter){
    StringBuilder sb = new StringBuilder();
    for (char ch : theString.toCharArray()) {
        if (ch == keyCharacter) {
            sb.append('$'); // <-- mask keyCharacter(s).
        } else {
            sb.append(ch); // <-- it isn't the character to mask
        }
    }
    return sb.toString();
}

I wouldn't use a StringBuilder : just use the result of toCharArray() directly: 我不会使用StringBuilder :直接使用toCharArray()的结果:

char[] cs = theString.toCharArray();
for (int i = 0; i < cs.length; ++i) {
  if (cs[i] == keyCharacter) cs[i] = '$';
}
return new String(cs);

Not only is it more concise, but: 它不仅更简洁,而且:

  • It will run faster, because it's cheaper to access an array element than to invoke a method; 它运行得更快,因为访问数组元素比调用方法更便宜; and because it doesn't require StringBuilder's internal buffer to resize (although you could just pre-size that); 并且因为它不需要StringBuilder的内部缓冲区来调整大小(尽管你可以预先调整大小);
  • It will use less memory, because it doesn't require storage for the copy inside StringBuilder. 它将使用更少的内存,因为它不需要存储StringBuilder中的副本。

public static String maskCharacter(String theString, char keyCharacter){ public static String maskCharacter(String theString,char keyCharacter){

String masked = "";
for (int i = 0 ; i < theString.length() ; i++) {

    if (theString.charAt(i) == keyCharacter) {
         masked += "$";
    } 
    else {
        masked+=theString.charAt(i)+"";
    }
}
return masked;

} }

An answer that only uses string concatenation and basic character access. 仅使用字符串连接和基本字符访问的答案。

You seem to know that you can concatenate something to a string and get a different string. 您似乎知道可以将某些内容连接到字符串并获取不同的字符串。

maskedString = maskedString + ...;

You also know you can build a for-loop that gets each individual character using .charAt() 您还知道可以构建一个使用.charAt()获取每个单独字符的for循环

for (int k = 0; k < theString.length(); k++) {
    char nch = theString.charAt(k);
}

You can check equality between chars 您可以检查字符之间的相等性

if (nch == keyCharacter)

... assuming you know about else-branches, isn't it clear you just need to put them together? ...假设你知道其他分支,是不是很清楚你只需要将它们放在一起?

if (nch == keyCharacter) {
    // append '$' to maskedString
}
else {
    // append nch to maskedString
}

Of course this creates a new string on every loop iteration so it is not terribly efficient. 当然,这会在每次循环迭代时创建一个新字符串,因此效率不高。 But I don't think that's the point of the exercise. 但我认为这不是演习的重点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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