Home java How to convert char to int, without changing the encoding. Working with...

How to convert char to int, without changing the encoding. Working with StringBuffer

Author

Date

Category

The problem of my method-convert each number type StringBuffer into an array of int.

When attempting to convert each symbol “9 8 7 6 5 4 3 2 1” a retracted space I get the result: {57,56,55,54,53,52,51,50,49}

How can I put into an array of the same number as in the line?

public static void main (String [] args) {
StringBuffer strB = new StringBuffer ( "9 8 7 6 5 4 3 2 1");
int arrInt = strBToArrInt (strB);
for (int i = 0; i & lt; arrInt.length; i ++) {System.out.print (arrInt [i] + "");}
} // end main
int [] strBToArrInt (StringBuffer strBuff) {
strBuff = new StringBuffer (. strBuff.toString () replace ( "", ""));
int [] arrInt = new int [strBuff.length ()];
for (int i = 0; i & lt; arrInt.length; i ++) {
      arrInt [i] = Integer.valueOf (strBuff.charAt (0)); // I think -problemma encoded.
  strBuff.deleteCharAt (0); // remove the null character
}
  return arrInt;
} // end strBToArrInt

Answer 1, Authority 100%

In your case, it returns the character ASCI-code. You should use the method digit . Replace

arrInt [i] = Integer.valueOf (strBuff.charAt (0));

In

arrInt [i] = Character.digit (strBuff.charAt (0), 10);

But this method is fit only for numbers. If you have numbers, you first need to break up the original string on an array of strings using the method split .

.

String [] stringsArray = strBuff.toString () trim () split ( "\\ s +").;

And then go and parse each line as the number of

int [] arrInt = new int [stringsArray.length ()];
for (int i = 0; i & lt; stringsArray.length; i ++) {
  arrInt [i] = Integer.parseInt (stringsArray [i]);
}

Answer 2, Authority 20%

Convert string into an array of characters:

char [] = String.toCharArray ();

Use the int [i] = Character.getNumericValue (char [i]); .
Of course, in your case, use the charAt (); , where in the same row can be converted to the int

.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions