-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 ツ
  • 45,713
  • 17
  • 64
  • 91
diwa
  • 159
  • 2
  • 2
  • 10

6 Answers6

2

Use:

String[] ritcountry_ary = right_country.split(", ");
Pooya
  • 5,863
  • 3
  • 20
  • 41
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
  • 191,680
  • 20
  • 149
  • 239
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,692
  • 3
  • 20
  • 40
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 ツ
  • 45,713
  • 17
  • 64
  • 91
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,426
  • 4
  • 17
  • 39
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