Why does the foreach statement not change the element value?

前端 未结 6 1051

How come the following prints boss and not bass?

String boss = \"boss\";
char[] array = boss.toCharArray();

for(char c : array)
{
 if (c== \'o\')
     c =          


        
6条回答
  •  -上瘾入骨i
    2020-11-22 01:13

    You variable c gets changed, but not the array contents. To change the array, don't use c, manipulate the array directly.

    for(int i = 0; i < array.length; i++)
    {
     char c = array[i];
     if (c== 'o')
         array[i] = 'a';
    }
    

提交回复
热议问题