java 为什么不是方法 toLowerCase(); 在我的代码中工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4422469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:17:44  来源:igfitidea点击:

Why isn't the method toLowerCase(); working in my code?

java

提问by WM.

import java.util.Scanner;

public class Test
{

    public static void main(String[] args)
    {
        char[] sArray;

        Scanner scan = new Scanner(System.in);

        System.out.print("Enter a Palindrome : ");

        String s = scan.nextLine();


        sArray = new char[s.length()];

        for(int i = 0; i < s.length(); i++)
        {
            s.toLowerCase();
            sArray[i] = s.charAt(i);
            System.out.print(sArray[i]);
        }

    }
}

回答by Darin Dimitrov

It doesn't work because strings are immutable. You need to reassign:

它不起作用,因为字符串是不可变的。您需要重新分配:

s = s.toLowerCase();

The toLowerCase()returns the modified value, it doesn't modify the value of the instance you are calling this method on.

toLowerCase()返回修改后的值,它不会改变你调用此方法的实例的值。

回答by Brian

You need to do:

你需要做:

String newStr = s.toLowerCase();