为什么 toLowerCase 不会将字符串元素转换为小写?

huangapple go评论83阅读模式
英文:

Why won't toLowerCase convert the string element as lowercase?

问题

为什么这不会将字符串元素转换为小写?
给定字符串输入,转换为字符串数组。我希望每个单词都是小写的。然而,当我调试时,我注意到数组中的元素仍然在不同的大小写情况下变化。

String[] words = paragraph.split(" ");      //[how, to, do, in, java]
for(String word : words){
    word = word.toLowerCase();
}
英文:

Why won't this convert the string element as lowercase?
Given string input, converted into a string array. I want each word to be lowercase. However, when I debug, I notice the elements in my array are still varying in cases.

   String[] words = paragraph.split(" ");      //[how, to, do, in, java]
    for(String word : words){
        word = word.toLowerCase();
    }

答案1

得分: 2

因为通过执行toLowerCase(),你正在实例化一个新的String。所以你的word变量不再是对数组项的引用。

要么将toLowerCase()的结果添加到一个新数组中,要么使用索引进行循环:

for (i = 0; i < words.size(); i++) {
    words[i] = words[i].toLowerCase();
}
英文:

Because by doing toLowerCase(), you are instantiating a new String. So your word variable is no more a reference to an item of your array.

Either you add the result of the toLowerCase() to a new array or you loop with index :

for(i = 0;i &lt; words.size();i++) {
    words[i] = words[i].toLowerCase();
}

答案2

得分: 2

toLowerCase将返回一个new对象,你必须将它存储。

你可以使用Java 8在一行中实现:

Arrays.setAll(words, i -> words[i].toLowerCase());
英文:

toLowerCase will return a new object, you have to store it.

You can use Java 8 to achieve it in one line:

Arrays.setAll(words, i -&gt; words[i].toLowerCase());

答案3

得分: 1

你没有修改你的数组,而是将小写字符串赋值给了单词实例
你可以使用经典的for循环,将小写值赋值给数组的当前索引

例如,你的for循环应该如下所示:

for (int i = 0; i < words.length; i++) {
    words[i] = words[i].toLowerCase();
    System.out.println(words[i]);
}
英文:

You are not modifying your array instead you are assigning the lowercase string to the word instance
You can use the classic for loop and assign the lowercase value to the current index of the array

for en example, your for loop should look like

for(int i=0;i&lt; words.length;i++){
	words[i] = words[i].toLowerCase();
    System.out.println(words[i]);
}

答案4

得分: 0

字符串对象默认是不可变的。当您将某个内容重新赋值给字符串时,它会创建一个新的对象,因此数组中单词的原始字符串对象保持不变。

英文:

String objects are immutable by default. When you reassign something to string it creates a new object, hence the original String object in words array remain the same.

huangapple
  • 本文由 发表于 2020年5月4日 06:57:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/61582730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定