简体   繁体   中英

How do I convert a String to array Integer?

I am trying to convert String to array then to an Integer ,i made code working successfully in java ,but in android studio the array the i converted don't take the last value of array covered from string

   String y="abc";
    String[] array = y.split("");
    int[] x = new int[y.length()];
    for (int i=0;i<y.length();i++)

    {

       String letter=array[i];
        if( letter.equals("a")){x[i]=1;}
        if( letter.equals("b")){x[i]=2;}
        if( letter.equals("c")){x[i]=3;}

        sum =sum + x[i];
    }

sum variable always dont count the last value of conversation ,it should be 6 but i get 3

You should define "sum" outside your loop. To keep the value.

String y="abc";
String[] array = y.split("");
int[] x = new int[y.length()];
int sum = 0; 

for (int i=0;i<y.length();i++) {
    String letter=array[i];

    if( letter.equals("a")){x[i]=1;}
    if( letter.equals("b")){x[i]=2;}
    if( letter.equals("c")){x[i]=3;}

    sum += x[i];
}

Change your code to:

int sum = 0;
String str = "abc";
char letter = ' ';
char[] charArray= str.toCharArray();  //or use str.split (to a string array)

for (int i=0; i < str.length(); i++)
{
    letter = charArray[i];
    if(letter == 'a'){ sum += 1; }
    else if(letter == 'b'){ sum += 2; }
    else if(letter == 'c'){ sum += 3; }
}

This will split the string into an charArray and will than compare the character with the corresponded letter, and will perform the calculation based on the check.

Check this for the result

Good luck!

Update

The below answer is based on Android Studio debugger output. Seems a weird issue.

array will be {"","a","b","c"} with size 4 & hence for loop skips the last position since y.length()=3 . Try

int[] x = new int[array.length];

See the answer to this question Split string into array of character strings & Why in Java 8 split sometimes removes empty strings at start of result array? & for more reference

Solved the Android Studio issue by :

string.split("(?!^)")

For complete reference see below code :

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

    String y="abc";
    int sum=0;
    String[] array = y.split("(?!^)");
    int[] x = new int[array.length];
    for (int i=0;i<y.length();i++)
    {
        String letter=array[i];
        if( letter.equals("a")){x[i]=1;}
        if( letter.equals("b")){x[i]=2;}
        if( letter.equals("c")){x[i]=3;}

        sum =sum + x[i];
    }
    System.out.println("value of sum : "+sum+"");
}

And this time definitely sum is having value 6 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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