如何在android中增加字母数字? [关闭]

Posted

技术标签:

【中文标题】如何在android中增加字母数字? [关闭]【英文标题】:How to increment alphanumeric number in android? [closed] 【发布时间】:2019-02-27 15:38:20 【问题描述】:

我是 android 编码实践的新手

ABB20180001 假设这是我的第一个 ID,我希望使用共享首选项将其自动增加 1 并用作员工 ID。 如ABB20180002、ABB20180003、ABB20180004等

【问题讨论】:

ABB20180001 不是有效的int 我的朋友,你不能增加它 是十六进制数吗?你打算使用所有字符,还是只使用ABCDEF 它只是字母数字,我需要 ABB20180002、ABB20180003 等 【参考方案1】:

您可以使用特定的radix 将数字解析为long,将其递增,然后将其转换回String。

如果您使用所有字母,则可以使用36 作为基数:

long number = Long.parseLong("ABB20180001", 36);

String incremented = Long.toString(number + 1, 36).toUpperCase();//"ABB20180002"

您的数字可能只是一个十六进制数字。在这种情况下,您可以使用16 作为基数,而不是如上所示的36

请注意,如果 ABB 只是一个前缀,那么上面的方法将不起作用(增加 20 将返回 ABB2018000L)。

如果"ABB" 只是一个静态前缀,那么你可以使用

//if the prefix changes, a regex will be needed
String incremented = "ABB" + (Long.parseLong(string.replace("ABB", "")) + 1)

最后,如果"ABB" 可以更改,您可以使用这样的正则表达式(下面的示例假设前缀长度为 3,相应更改):

String s = "ABB20180001";
String[] parts = s.split("(?<=[A-Z]3)"); //split after a sequence of 3 letters
String res = parts[0] + (Long.parseLong(parts[1]) + 1);

【讨论】:

几天前我在检查parseInteger 的工作原理,但是在阅读这个问题时,并没有弄清楚它可以在这里使用。我喜欢第一种方法! 这应该被接受。 +1 为基数方法。【参考方案2】:

您不能直接增加字母数字值。如果想这样做,你需要为它写几行代码

这里是 activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txt_autoincreament"
        android:layout_
        android:layout_
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:layout_
        android:layout_
        android:text="click"
        android:onClick="Click"/>

</LinearLayout>

这里是 MainActivity.java

public class MainActivity extends AppCompatActivity 
    TextView autoTextIncreament;
    String stringValue="ABB";
    long intValue=20180001;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        autoTextIncreament = findViewById(R.id.txt_autoincreament);
    

    public void Click(View view)
        autoTextIncreament.setText(getValue());
    

    private String getValue() 
        return stringValue+String.valueOf(intValue++);
    

希望这会对你有所帮助。

【讨论】:

您的答案是递增值并将其与一些预定义的字符串连接。您添加 Android 代码的原因是什么? 我通过添加几行代码将帮助他快速理解。因为他是安卓开发的新手。

以上是关于如何在android中增加字母数字? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

如何使用字母和数字自动增加 ID 编号

当我输入字母像m我在笔记本电脑中得到像0值的数字如何修复[关闭]

HTML & JS 问题:如果按下数字、符号或字母键,如何将焦点放在 HTML 输入元素上[关闭]

转换数字+字母字符串[关闭]

如何屏蔽信用卡号的前两个字母和后四个字母[关闭]

如何实现android EditText允许输入字母和数字,同时默认弹出数字键盘?