简体   繁体   中英

Need to split a string using a delimiter and store its values in a Constructor (Java)

Song(String info): Initialize a Song by parsing a String that contains the title, artist, and time with a semicolon and a space used as the delimiter. For example, the info String for the song "Where the Streets Have No Name" by U2 is

java "Where the Streets Have No Name; U2; 5:36"

The time is given as a number of hours, minutes, and seconds separated by colons. The minutes and seconds are numbers between 0 and 59. If the song is less than an hour, only the minutes and seconds are given. Similarly, if the song is less than a minute, only the seconds are given.

Here is my code so far:

import java.util.Arrays;

public class Song {
    
    private String title;
    private String artist;
    private int[] time;
    private static final String INFO_DELIMITER = "; ";
    private static final String TIME_DELIMITER = ":";
    private static final int IDX_TITLE = 0;
    private static final int IDX_ARTIST = 1;
    private static final int TIME = 2;
    
    public Song(String title, String artist, int[] time) {
        this.title = title;
        this.artist = artist;
        this.time = Arrays.copyOf(time, time.length);
    }
    public Song(String info) {
        String words[] = info.split(INFO_DELIMITER);
            this.title = words[0];
            this.artist = words[1];
            
            String temp = words[2];
            this.time = Arrays.copyOf(Integer.parseInt(words[2], Integer.parseInt(words[2].length)));
    }
    
    public String getTitle() {
        return title;
    }
    
    public String getArtist() {
        return artist;
    }
    
    public int[] getTime() {
        return Arrays.copyOf(time, time.length);
    }
    
    public String toString() {
        
    }
}

You should split the word containing time using TIME_DELIMITER .

If it is possible to use Java 8 Stream API, time can be set as follows:

this.time = Arrays.stream(temp.split(TIME_DELIMITER))
                  .mapToInt(Integer::parseInt)
                  .toArray();

or using old-style coding:

String[] strTime = word[2].split(TIME_DELIMITER);
time = new int[strTime.length];
for (int i = 0; i < strTime.length; i++) {
    time[i] = Integer.parseInt(strTime[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM