java - 更改字符串中的某些字符

标签 java string chars

我是一名初学者程序员,我正在尝试制作一个非常简单的 Hangman 版本。我的代码有很大问题。这是我遇到问题的代码部分:

        for(int i = 0; i <= wordLength - 1; i++ ) {

            if (letter == theWord.charAt( i )) {

                onemore=i+1;
                System.out.println("This letter matches with letter number " + onemore + " in the word.");
                ***displayWord.charAt(i)=letter;***
                System.out.println("The word so far is " + displayWord);
            } 

        }

我遇到错误的部分两侧各有 3 个星号。

displayWord 是一个字符串,而 letter 是一个字符。

Netbeans 告诉我:

unexpected type
  required: variable
  found:    value

我不知道问题是什么。

最佳答案

基本上,Java String 是不可变的,即内容无法更改。

您最好使用StringBuilder

String theWord = "This is a simple test";
char letter = 'i';
char changeTo = '-';

StringBuilder displayWord = new StringBuilder(theWord);

int i = theWord.indexOf(letter);
if (i != -1) {
    System.out.println("This letter matches with letter number " + (i + 1) + " in the word.");
    displayWord.setCharAt(i, changeTo);

    System.out.println("The word so far is " + displayWord);
}

System.out.println(displayWord);

这会导致:

This letter matches with letter number 3 in the word.
The word so far is Th-s is a simple test
This letter matches with letter number 6 in the word.
The word so far is Th-s -s a simple test
This letter matches with letter number 12 in the word.
The word so far is Th-s -s a s-mple test
Th-s -s a s-mple test

现在简短的版本可能看起来像这样

String displayWord = theWord.repace(letter, changeTo);

关于java - 更改字符串中的某些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11876328/

相关文章:

c# - 在一定字符数后拆分字符串

Java - 逐字符读取文件并计算行数

java - 如何在play framework中编写模板测试代码?

java - 服务器如何向其他客户端广播消息?

java - 将 ImageJ 宏命令实现到现有插件中

c - 如何读取字符串

java - Eclipse Lombok 构建器添加新建议

php - 为什么答案是15?

java - 测试输入的前两个字符是否为字母数字 - 无正则表达式

Java/Android : how to find the first characters of a string if it equals other string