更改字符串中的某些字符

时间:2012-08-09 03:21:58

标签: 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);
            } 

        }

我收到错误的部分有两个星号。

displayWord是一个字符串,字母是一个字符。

Netbeans告诉我:

unexpected type
  required: variable
  found:    value

我不知道问题是什么。

4 个答案:

答案 0 :(得分:4)

基本上,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);

答案 1 :(得分:0)

我不确定这个错误,但在Java中你不能用这样的样式更新角色。

相反,请尝试使用StringBuilder作为displayWord。这有一个方法:setCharAt可能是你想要的。

祝你好运编码:)

答案 2 :(得分:0)

charAt(i)返回单词的那一部分的字母值,你不能用它来改变这个值。 Java中的字符串是不可变的,因此您实际上无法更改此字符串。您可以创建一个新的(使用构造函数或者可能的replaceXXX函数之一)并将其分配回displayWord,或者查看StringBuffer类,它对这类事物更有效。

答案 3 :(得分:0)

由于String是不可变对象,因此无法更改其内容。不可变意味着一旦设置String的内容,您就无法以任何方式更改它。您可以随时更改引用,但不能更改内容本身。

话虽如此,String对象并未提供任何违反此原则的方法。没有setCharAt,您无法为charAt(i)的结果分配新值。请注意一些“似乎”更改String(如replace)的方法是如何返回一个带有更改的新克隆对象。例如:

String sample = "Hello World!";
sample.replace('e', '*');
System.out.println(sample);

以上代码sample进行任何更改,因此屏幕上显示的结果将为Hello World!。为了捕获replace方法所做的更改,我们需要将sample变量重新分配给replace的结果:

String sample = "Hello World!";
sample = sample.replace('e', '*');
System.out.println(sample);

在这种情况下,我们使用sample返回的新克隆String更新我们的replace变量。此值将包含更改,因此我们将打印出H*llo World!

现在你知道为什么你不能改变String的内容,让我们看看你有什么解决方案。

  1. 首先,为了保持程序的确切行为,最好的方法是使用像之前指出的@MadProgrammer这样的StringBuilder。查看StringBuilder类的过于简单的方法基本上是一个可变的String。有了它,您可以进行各种替换和修改。

  2. 另一种解决方案(不建议使用)是在每次要更改角色时使用String来创建新副本。这将是非常麻烦的,并没有优于StringBuilder解决方案的优势,所以我不打算详细介绍。

  3. 第三种解决方案取决于您的要求以及您的灵活性。如果你要做的就是替换String中某个特定字符的每一个字母,那么你的代码可以简化很多,你可以使用我之前谈过的replace方法。它将类似于:

    String theWord =“这是我们的测试字符串”; char letter ='e'; char changeTo ='*'; String displayWord = theWord.replace(letter,changeTo); System.out.println(“生成的单词是:”+ displayWord);

  4. 这将输出以下结果:

    The resulting word is: H*r* is our t*sting string
    

    同样,这仅适用于您的要求足够灵活且您可以跳过您在示例代码中遵循的“逐步”方法。