【问题标题】:Why is .toCharArray() giving garbage value? [duplicate]为什么 .toCharArray() 给出垃圾值? [复制]
【发布时间】:2021-10-06 21:12:18
【问题描述】:

下面提到的代码用于反转 n 大小的字符串中的 k 个元素。第 3 行正在返回垃圾值。谁能帮我解决这个问题。

class Solution{
     public String reverseStr(String s, int k){
        char[] ch = s.toCharArray();
        Stack<Character> st = new Stack();
         int i;
        for(i = 0; i < k; i++){
            st.push(ch[i]);
        }
         i = 0;
         while(!st.isEmpty()){
             ch[i] = st.pop();
         }
         return ch.toString();
     }
}

【问题讨论】:

  • “垃圾值”是什么意思?
  • 举一个输入输出字符串的例子。
  • Answer by Jesper 是正确的,应该被接受以解决您的特定问题。但是,使用 char 的此类代码已过时。 char 类型甚至无法表示由 Unicode 定义并由 Java 支持的一半字符。相反,学习使用 Unicode code point 整数。请参阅适用于代码点 run live at IdeOne.com 的代码版本。我的代码处理"dog????" 的输入,而您的代码中断。

标签: java string data-structures stack


【解决方案1】:

递增i

您的这部分代码有错误:

i = 0;
while(!st.isEmpty()){
    ch[i] = st.pop();
}

请注意i 始终保持0,因此您在循环的每次迭代中分配给ch[0]。您可能打算在循环中增加 i

i = 0;
while(!st.isEmpty()){
    ch[i++] = st.pop();
}

char 数组生成String

注意代码的最后一行:

return ch.toString();

not return what you expect。如果要将char 数组转换为包含字符的String,请改为:

return new String(ch);

【讨论】:

  • 即使是固定的,虽然“垃圾”是默认的toString()
  • @chrylis-cautiouslyoptimistic- 实际上,这是另一个错误,已添加到我的答案中。
  • 他必须在函数启动后添加空检查条件 if (s != null )
猜你喜欢
  • 1970-01-01
  • 2021-02-20
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多