简体   繁体   English

在Java中将复杂的字符串解析为整数集

[英]Parsing a complex string into sets of integers in Java

I'm a beginner programmer and I was tasked an assignment to calculate total money spent on phone calls, a String of phone numbers and call time. 我是一名初学者程序员,我被分配了一项任务来计算电话总花费,一串电话号码和通话时间。 Making calculations is easy for me however parsing the string itself is quite challenging. 对我来说,进行计算很容易,但是解析字符串本身是非常困难的。 I need to convert a String containing semicolons, commas and newlines into sets of phone numbers and total call time which are integers. 我需要将包含分号,逗号和换行符的String转换为电话号码和总通话时间(整数)的集合。 The string looks like this: 该字符串如下所示:

hh:mm:ss,nnn-nnn-nnn
hh:mm:ss,nnn-nnn-nnn
hh:mm:ss,nnn-nnn-nnn

I know that I would be able to parse by line if I was reading a text file using scanner and a hasNext function, so should I utilize \\n somehow? 我知道如果我使用扫描仪和hasNext函数读取文本文件,就可以逐行进行解析,那么我应该以某种方式使用\\n吗? Using the split(":") would not get me very far. 使用split(":")不会使我走的太远。

Any other things that can be helpful? 还有其他有用的东西吗? Any help or useful information would be appreciated! 任何帮助或有用的信息将不胜感激!

You can use the split function and just specify every token to split at with "[]" for example use split("[ ,:-]") 您可以使用split函数,只需使用"[]"指定要分割的每个标记,例如,使用split("[ ,:-]")

the code 编码

String number = "11:22:33,444-555-666";
String[] numbers = number.split("[ ,:-]");
for (String temp: numbers){
System.out.println(temp);

Gives the result 给出结果

11 22 33 444 555 666 11 22 33 444 555 666

You could just perform multiple splits, first to separate the time from the phone number, then to separate the individual parts of each. 您可以执行多个拆分,首先将时间与电话号码分开,然后将每个部分分开。 For example: 例如:

Scanner sc = new Scanner(inputStr);

while (sc.hasNextLine()) {
    String line = sc.nextLine();
    String parts[] = line.split(",");
    String time[] = parts[0].split(":");
    String phone[] = parts[1].split("-");
    // Process the time and phone number here
}

The variable parts has two elements, the time and the phone number. 可变部分有两个元素,时间和电话号码。 The variable time contains the three elements of the time, and phone contains the three elements of the phone number. 可变时间包含时间的三个元素,电话包含电话号码的三个元素。

I prefer Regular Expressions and Pattern/Matcher for this type of task: 对于这种类型的任务,我更喜欢使用正则表达式和模式/匹配器:

        private static final String REGEX =
        "..:..:..,...-...-...";

    private static final String INPUT = "h1:m1:s1,nnn-nnn-nnn   \n"
            + "   h2:m2:s2,nnn-nnn-nnn   \n"
            + " hh:mm:ss,nnn-nnn-nnn";

    public static void main(String[] args) {
       Pattern p = Pattern.compile(REGEX);
       Matcher matcher = p.matcher(INPUT);
       while(matcher.find()) {
           String timePhoneNumber = matcher.group(0);
           String tokens[] = timePhoneNumber.split(",");
           String time = tokens[0];
           String phoneNumber = tokens[1];
           System.out.println("Time="+time+"; phone="+phoneNumber);
      }
   }
public class MultiSplit {

    public static void main(final String[] args) {
        final String INPUT = "14:23:51,n11-n12-n13   \n"//
                + "   15:24:46,n21-n22-n23   \n" //
                + "   15:2a:46,n21-n22-n23   \n" // error
                + "\n" // error
                + "null\n" // error
                + " 12:11:10,n31-n32n33  \n" // error
                + " 12:1111,n31-n32n33  \n" // error
                + " 12:11:12,n31-n32-n33\n";

        final String[] dirtyLines = INPUT.split("\n");

        System.out.println("MODE 1");
        for (final String dirtyLine : dirtyLines) {
            try {
                final String cleanLine = dirtyLine.trim();
                final String line = cleanLine.replace(",", ":");
                final String[] parts = line.split(":");

                final int hour = Integer.parseInt(parts[0]);
                final int minute = Integer.parseInt(parts[1]);
                final int second = Integer.parseInt(parts[2]);
                final String phone = parts[3];
                System.out.println("h:" + hour + "\tm:" + minute + "\ts:" + second + " \t => " + phone);

            } catch (final Exception e) {
                System.err.println("Error on line <" + dirtyLine + ">: " + e);
            }
        }

        System.out.println("\n\nMODE 2");
        for (final String dirtyLine : dirtyLines) {
            try {
                final String cleanLine = dirtyLine.trim();
                final String line = cleanLine.replace(",", ":").replace("-", ":");
                final String[] parts = line.split(":");

                final int hour = Integer.parseInt(parts[0]);
                final int minute = Integer.parseInt(parts[1]);
                final int second = Integer.parseInt(parts[2]);
                final String phone1 = parts[3];
                final String phone2 = parts[4];
                final String phone3 = parts[5];
                System.out.println("h:" + hour + "\tm:" + minute + "\ts:" + second + " \t => " + phone1 + "#" + phone2 + "#" + phone3);

            } catch (final Exception e) {
                System.err.println("Error on line <" + dirtyLine + ">: " + e);
            }
        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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