【问题标题】:CharSequence to intCharSequence 到 int
【发布时间】:2011-08-17 00:42:54
【问题描述】:

有没有办法将字符序列或字符串转换为 Ingeter?

CharSequence cs = "123";
int number = (int) cs;

我是菜鸟。解决方案:

CharSequence cs = "123";
int number = Integer.parseInt(cs);

【问题讨论】:

  • 反之怎么样?
  • CharSequence cs = String.valueOf(number);
  • @passsy 您的评论应该是推荐的选项。而不是不必要的转换。

标签: java android int charsequence


【解决方案1】:

使用这个

int i=Integer.parseInt(cs.toString())

【讨论】:

    【解决方案2】:

    Integer.parseInt(cs.toString())

    【讨论】:

      【解决方案3】:

      使用 Wrapper 类(Integer、Float 等)中的解析器...

      public static void main(String[] args) {
          String s = "1";
          int i = Integer.parseInt(s);
          System.out.println(i);
      }
      

      【讨论】:

        【解决方案4】:

        使用Integer.parseInt()。如果您的CharSequence 不是String,则需要先使用toString() 进行转换。

        int number = Integer.parseInt(cs.toString());
        

        【讨论】:

        • 除了 Joachim 的回答之外,在您的情况下,CharSequence cs 已经是一个字符串。 CharSequence 是由 String 实现的 interface (但不仅如此),因此您没有创建 CharSequence 的对象(因为没有这样的东西),而是将 String 分配给 cs
        【解决方案5】:

        来自 Editview 组件,

        TextView txtYear = (TextView) findViewById(R.id.txtYear);
        int intYear = Integer.parseInt(txtYear.getText().toString());
        

        【讨论】:

          【解决方案6】:

          从 Java 9 开始,您可以使用 Integer.parseInt(CharSequence s, int from, int to, int radix) 解析来自任何 CharSequence 的整数,而无需先将其转换为字符串:

          CharSequence cs = new StringBuilder("4711");
          int value = Integer.parseInt(cs, 0, cs.length(), 10);
          

          【讨论】:

            【解决方案7】:

            使用 Kotlin

            CharSeqString.toString.toInt()
            

            【讨论】:

              猜你喜欢
              • 2011-03-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多