-4

I would like to convert the string to string array in java. I tried the following method to achieve this. But its not working as expected.

String right_country = "BH, MY, SG, IN, AE";
String[] ritcountry_ary = new String[] {right_country};

When try to print the above array this is what i am getting.

for(int i=0 ;i<=countries.length - 1; i++){

            System.out.println("o"+countries[i]);
        }

output:oBH, MY, SG, IN, AE

But I need something like the following.

oBH
oMY
oSG
oIN
oAE
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
diwa
  • 169
  • 2
  • 2
  • 11

6 Answers6

2

Use:

String[] ritcountry_ary = right_country.split(", ");
Pooya
  • 6,083
  • 3
  • 23
  • 43
1

Instead of creating an array of one element, split your right_country on , (and optional white space). And, I would prefer a for-each loop. Something like,

String right_country = "BH, MY, SG, IN, AE";
String[] ritcountry_ary = right_country.split(",\\s*");
for (String country : ritcountry_ary) {
    System.out.println("o" + country);
}

Output is (as requested)

oBH
oMY
oSG
oIN
oAE
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Try using the split function.

String[] ritcountry_ary = right_country.split(", ");

This function makes an array out of the string by splitting it based on the text you pass it.

nhouser9
  • 6,730
  • 3
  • 21
  • 42
0

Try using String.split to get an array and use the correct array in the for loop:

public static void main(String[] args) {
        String right_country = "BH, MY, SG, IN, AE";
        String[] ritcountry_ary =right_country.split(", ");
        for(int i=0 ;i<ritcountry_ary.length; i++){
            System.out.println("n"+ritcountry_ary[i]);
        }
    }
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

new String[] {right_country} merely creates a new array of String objects with a single element in the array. Assuming that right_country looks like "BH, MY, SG, IN, AE", you can split them into an array using a regular expression:

String right_country = "BH, MY, SG, IN, AE";
String[] right_countries = right_country.split(",\\s*");
for (String country : right_countries) {
    System.out.println("o" + country);
}
errantlinguist
  • 3,658
  • 4
  • 18
  • 41
0

I think that what you need is the method split().

You should check this topic for more details : How to split a string in Java

It's very simple, you call split() on the source string, with separator as parameter, and it returns you an array :) This give you somethink like :

ritcountry_ary = right_country.split(", ");
Community
  • 1
  • 1