user841852
user841852

Reputation: 187

How Do I separate String from Integer and Save it

I wanted to know how can I separate a string into two parts and save it in two different variables.

I have:

String str = "3-abc";

And want to save it in two Strings:

String part1 = "3";
String part2 = "abc";

Any help will be highly appreciated, Thanks

Upvotes: 0

Views: 483

Answers (4)

evilone
evilone

Reputation: 22750

If strings are all in one format you can use String[] splittedStrings = str.split("-"); After that try to convert your string to integer with Integer.parseInt(splittedStrings[0]);

Upvotes: 0

dku.rajkumar
dku.rajkumar

Reputation: 18588

String[] strArray = str.split("-");
String part1=strArray[0]; 
String part2=strArray[1];

Upvotes: 2

Paul Varghese
Paul Varghese

Reputation: 1655

You can use split function

String[] temp;
String delimiter = "-";
temp = str.split(delimter);
for(int i =0; i < temp.length ; i++)
   System.out.println(temp[i]);

Upvotes: 2

Jomoos
Jomoos

Reputation: 13083

You can use the split method of String class. So

String[] parts = str.split("-");

String part1 = parts[0];
String part2 = parts[1];

From Java Documentation:

Splits this string around matches of the given regular expression. 


Returns:
    the array of strings computed by splitting this string around 
    matches of the given regular expression 

Upvotes: 1

Related Questions