简体   繁体   English

charAt() 方法如何从字符串中获取数字并将它们放入 Java 中的新字符串中?

[英]How does the charAt() method work with taking numbers from strings and putting them into new strings in Java?

public String getIDdigits()
    {
        String idDigits = IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1) + "";
        return idDigits;
    }

In this simple method, where IDnum is a 13 digit string consisting of numbers and is a class variable, the given output is never what I expect.在这个简单的方法中,其中 IDnum 是一个由数字组成的 13 位字符串并且是一个 class 变量,给定的 output 绝不是我所期望的。 For an ID number such as 1234567891234, I would expect to see 14 in the output, but The output is always a three-digit number such as 101. No matter what ID number I use, it always is a 3 digit number starting with 10. I thought the use of empty quotation marks would avoid the issue of taking the Ascii values, but I seem to still be going wrong.对于像 1234567891234 这样的 ID 号,我希望在 output 中看到 14,但是 output 始终是三位数,例如 101。无论我使用什么 ID 号,它总是以 3 开头的数字.我认为使用空引号可以避免取 Ascii 值的问题,但我似乎仍然会出错。 Please can someone explain how charAt() works in this sense?请有人能解释一下 charAt() 在这个意义上是如何工作的吗?

Try this.尝试这个。

public String getIDdigits()
    {
        String idDigits = "" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1);
        return idDigits;
    }

When you first adding a empty it's add char like String if you put it in end it first add in number mode(ASCII) and then convert will converts that to String .当你第一次添加一个空时,如果你把它放在最后,它会像String一样添加char ,它首先添加数字模式(ASCII),然后 convert 将其转换为String

You are taking a char type from a String and then using the + operator, which in this case behaves by adding the ASCII numerical values together.您正在从String中获取char类型,然后使用+运算符,在这种情况下,它的行为是将 ASCII 数值加在一起。

For example, taking the char '1' , and then the char '4' in your code例如,在您的代码中使用 char '1' ,然后是 char '4'

IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1)

The compiler is interpreting this as its ASCII decimal equivalents and adding those编译器将其解释为其 ASCII 十进制等价物并添加这些

49 + 52 = 101

Thats where your 3 digit number comes from.这就是您的 3 位数号码的来源。

Eradicate this with converting them back to string before concatenating them...通过在连接它们之前将它们转换回字符串来消除这种情况......

String.valueOf(<char>);

or或者

"" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1)

You have to be more explicit about the string concatenation and so solve your statement like this:您必须更明确地了解字符串连接,因此像这样解决您的语句:

String idDigits = "" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1);

The result of adding Java chars, shorts, or bytes is an int:添加 Java 字符、短裤或字节的结果是一个 int:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM