Home > front end >  Splitting a String with different inputs Java
Splitting a String with different inputs Java

Time:10-03

Input = computer science: harvard university, cambridge (EXAMPLE)

Prompt: Use a String method twice, to find the locations of the colon and the comma. Use a String method to extract the major and store it into a new String. Use a String method to extract the university and store it into a new String. Use a String method to extract the city and store it into a new String. Display the major, university, and city in reverse, as shown below, followed by a newline.

I was thinking I could just use substring(); but the input entered from the user varies and so the indexes are all different. I am still learning and am stumped on how to do this one. Does substring let you somehow use it without knowing the specific index? Or do I have to use a whole different method? Any help would be awesome. BTW this is HW.

CodePudding user response:

Assuming the input string has format: <major>: <university>, <city>

String has a set of indexOf() methods to find the position of a character/substring (returns -1 if the character/substring is not found) and substring to retrieve a subpart of the input from index or between a pair of indexes.

Also, String::trim may be used to get rid of leading/trailing whitespaces.

String input = "computer science: harvard university, cambridge";

int colonAt = input.indexOf(':');
int commaAt = input.indexOf(',');

String major = null;
String university = null;
String city = null;
if (colonAt > -1 && commaAt > -1) {
    major = input.substring(0, colonAt);
    university = input.substring(colonAt   1, commaAt).trim();
    city = input.substring(commaAt   1).trim();
}

System.out.printf("Major: '%s', Univ: '%s', City: '%s'%n", major, university, city);

Output:

Major: 'computer science', Univ: 'harvard university', City: 'cambridge'

CodePudding user response:

You can use String.split(regex)

Ex:

String str = "[email protected]";
String[] parts = str.split("@");
String part1 = parts[0]; // abc
String part2 = parts[1]; // gmail.com
  •  Tags:  
  • java
  • Related