【问题标题】:Convert whole String in integer value in android在android中将整个字符串转换为整数值
【发布时间】:2013-02-16 13:16:04
【问题描述】:

在将整个字符串转换为整数时遇到问题。 当我在 edittext "Hello" 中写入时,当我按下按钮然后在其他 edittext 中时,它应该显示给我 72 101 108 108 111。 请帮帮我...

我的 .xml 文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >



    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"

        android:layout_marginRight="22dp"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:hint="@string/Message" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"

        android:text="@string/Decimal" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_marginTop="30dp"

        android:ems="10" 

        android:hint="@string/Decimal"/>

</RelativeLayout>

【问题讨论】:

  • 请发布您的代码..

标签: android string format decimal


【解决方案1】:

您必须将输入的字符串中的每个字符转换为 int。 下面的示例代码可能会对您有所帮助:

String str = "Hello";
String strInt = "";
for(int i=0;i<str.length();i++){
  char c = str.charAt(i);
  strInt += (int)c + " ";
}
System.out.println(strInt);

【讨论】:

    【解决方案2】:

    只需将字符转换为 int 即可获得 ascii 值。

    StringBuilder stringToAppendInts = new StringBuilder();
    StringBuilder stringToAppendHexs = new StringBuilder();
    
    for(char item : myString.toCharArray()){
       stringToAppendHexs.append(Integer.toHexString((int)item) +" ");
       stringToAppendInts.append( (int)item+" ");
    }
    
    edittext.setText(stringToAppendInts.toString());
    edittext.setText(stringToAppendHexs.toString());
    

    【讨论】:

    • 使用StringBuilderStringBuffer 而不是String 怎么样?您应该知道String 是不可变的,如果他会从一些大尺寸的 file.txt 生成例如文本,那么您的方法将消耗太多内存。
    • @Gjordis..你能告诉我如何将字符串转换为十六进制值吗..??
    • @sajmon_d 他问“字符串”。我用字符串回答
    • 现在它包含转换为十进制和十六进制整数。基数 10 和基数 16
    • @Gjordis 你应该告诉他这样做不好。然后看起来许多应用程序没有正确实现并且不安全。这是建议而非规则。
    猜你喜欢
    • 1970-01-01
    • 2011-05-09
    • 2017-06-11
    • 2011-02-12
    • 1970-01-01
    • 2013-12-29
    • 2021-12-14
    • 1970-01-01
    • 2014-10-06
    相关资源
    最近更新 更多