how to form a dynamic string array using java

srikotesh
srikotesh used Ask the Experts™
on
Hi Experts,
how to form a dynamic string array from the below inputs

String countries="sg,sk,hk,ke" //this string having country names dynamically
countries max will be five and min will be one value separated with comma(,)


i have to form dynamic string array based on above countries
user can choose any country but max will be 5 countries min 1 country
country values are dynacmic

how to form dynamic string array

exmaple:
new String[] {"sheet one"+ "sg" , "sheet two" + "sk","sheet three" + "hk","sheet four" + "ke","sheet five" + "ug","summary"}
new String[] {"sheet one"+ "sg" , "sheet two" + "sk","sheet three" + "hk","sheet four" + "ke","summary"}
new String[] {"sheet one"+ "sg" , "sheet two" + "sk","sheet three" + "hk","summary"}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016

Commented:
countries.split(",");

Open in new window

will give you String[] dynamically

Author

Commented:
hi cehj,
I have to add sheet names as well
 if the user choosen 3 countries

sheetname1+countryname
sheetname2+country name
sheetname3+countryname
summary

here sheet names I am adding based on no of countries choosen
at the end summary(constant) I have to add.

the only input I will get is country names.
sheet names,summary I have to add along with country names.
Top Expert 2016

Commented:
Well, you can iterate the array and do what you want with it
Software Engineer
Commented:
      Map<Integer, String> numbers = new HashMap<>();
      numbers.put(1, "one");
      numbers.put(2, "two");
      numbers.put(3, "three");
      numbers.put(4, "four");
      numbers.put(5, "five");
      numbers.put(6, "six");
      numbers.put(7, "seven");
      numbers.put(8, "eight");
      numbers.put(9, "nine");
      numbers.put(10, "ten");
      
      String countries = "sg,sk,hk,ke";
      
      String[] countryNames = countries.split(",");
      
      String[] results = new String[countryNames.length + 1];
      
      for (int index = 0; index < countryNames.length; index++)
         results[index] = "sheet " + numbers.get(index + 1) + ": " + countryNames[index];
      results[countryNames.length] = "summary";
      
      System.out.println(Arrays.toString(results));

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial