0

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

1

4 Answers 4

2
String[] strArray = str.split("-");
String part1=strArray[0]; 
String part2=strArray[1];
Sign up to request clarification or add additional context in comments.

Comments

2

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]);

Comments

1

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 

Comments

0

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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.