36

Is there a Way to converte a Charsequence or a String to an Ingeter?

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

I'm a Noob. Solution:

CharSequence cs = "123";
int number = Integer.parseInt(cs);
passsy
  • 5,162
  • 4
  • 39
  • 65

7 Answers7

68

Use Integer.parseInt(). If your CharSequence is not a String, then you need to convert it first using toString().

int number = Integer.parseInt(cs.toString());
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • In addition to the answer of Joachim, in your case the `CharSequence` cs is already a String. `CharSequence` is an `interface` implemented by String (but not only), so you didn't create an object of `CharSequence` (Since there is no such thing), but assigned a String to `cs`. – MByD May 02 '11 at 14:33
14

Since Java 9 you can use Integer.parseInt(CharSequence s, int from, int to, int radix) to parse integers from any CharSequence without first converting it to a String:

CharSequence cs = new StringBuilder("4711");
int value = Integer.parseInt(cs, 0, cs.length(), 10);
Claes Redestad
  • 509
  • 5
  • 8
5

use this

int i=Integer.parseInt(cs.toString())
Sunil Pandey
  • 7,042
  • 7
  • 35
  • 48
1

Integer.parseInt(cs.toString())

Kal
  • 24,724
  • 7
  • 65
  • 65
0

Use the parsers from the Wrapper classes (Integer, Float, etc)...

public static void main(String[] args) {
    String s = "1";
    int i = Integer.parseInt(s);
    System.out.println(i);
}
Lucas de Oliveira
  • 1,642
  • 11
  • 16
0

Using Kotlin

CharSeqString.toString.toInt()
Ajay P. Prajapati
  • 1,973
  • 1
  • 17
  • 34
-2

From Editview component,

TextView txtYear = (TextView) findViewById(R.id.txtYear);
int intYear = Integer.parseInt(txtYear.getText().toString());
Procrastinator
  • 2,526
  • 30
  • 27
  • 36
Joseph Selvaraj
  • 2,225
  • 1
  • 21
  • 21