dan
dan

Reputation: 107

Convert each character of string into integer

I have hard coded 'a to z' integers with their respective integer/number values. like

    int a=0, b=1, c=2, d=3, e=4, f=5, g=6;   

Now i have an edit text which can take input like abcdefg. I want to convert each character of string into int so that i can get 0123456 in return of abcdefg Is that possible? please help. Thanks in advance.

Upvotes: 1

Views: 2100

Answers (5)

Nermeen
Nermeen

Reputation: 15973

if you intend to modify the input in the edit text, i.e. when the user inters 'a' he see '1' instead..Try overriding addTextChangedListener use onTextChanged (if you want to modify it while the user is writing) or afterTextChanged (if you want to modify it after the user is done):

editText.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {

    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){
    }
    public void onTextChanged(CharSequence s, int start, int before, int count){
    }
}); 

Upvotes: 0

Hitesh Jain
Hitesh Jain

Reputation: 408

try using this

String text = "hitesh";
    char[] ch = text.toCharArray();
    StringBuilder sb = new StringBuilder();
    for(char cd :ch)
    {
        int n = cd-'a'; 
        sb.append(n);
    }
    System.out.println(sb.toString());

Upvotes: 0

Ram kiran Pachigolla
Ram kiran Pachigolla

Reputation: 21191

For this its better to use hashmap

delecare values in hash map as like below

HashMap<String,Integer> map = new HashMap<String,Integer>();
    map.put("a", 0);
    map.put("b", 1);
    map.put("c", 2);
    map.put("d", 3);
            //....
    map.put("z",25);


    String s1 ="abcdefg";//String from edit text
    char[] sa = s1.toCharArray();//converting to character array.
    String str ="";
    for(int i=0;i<sa.length;i++)
    {
        str = str+(map.get(Character.toString(sa[i])));
    }
    System.out.println(str);//Here str show the exact result what you required.

Upvotes: 2

Chirag
Chirag

Reputation: 56925

Its very simple . First you have to get string from edittext then convert it to string array and in for loop compare it.

String convertedText;
String str = editText.getText().toString();;
char[] ch = str.toCharArray();
for (char c : ch)
{
      System.out.println(c);
      if(c == 'a')
          convertedText = convertedText + "1"; 
      // Coding to compare each character
}

Upvotes: 1

cc4re
cc4re

Reputation: 4901

this can be done like this
ASCI value of a is 97 to get the value 0 subtract 97 so..

IN C

.......
char *insert = "abcdefg";
for (int i = 0; i < 7; ++i)
int value = ((digit_to_int(insert[i]))-97)+1
printf("%d", value );
.........



int digit_to_int(char d)
{
 char str[2];

 str[0] = tolower(d);
 str[1] = '\0';
 return (int) strtol(str, NULL, 10);
}

you can attain this

Upvotes: 0

Related Questions