Java String Split by Line splitInt(String line, String seperator, int def)

Here you can find the source of splitInt(String line, String seperator, int def)

Description

split Int

License

Open Source License

Declaration

public static int[] splitInt(String line, String seperator, int def) 

Method Source Code

//package com.java2s;
/**//from   w  w  w  .j a  v a 2 s  .co m
 * Tencent is pleased to support the open source community by making Tars available.
 *
 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * https://opensource.org/licenses/BSD-3-Clause
 *
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

import java.util.ArrayList;

public class Main {
    public static int[] splitInt(String line, String seperator, int def) {
        String[] ss = split(line, seperator);
        int[] r = new int[ss.length];
        for (int i = 0; i < r.length; ++i) {
            r[i] = convertInt(ss[i], def);
        }
        return r;
    }

    public static String[] split(String line, String seperator) {
        if (line == null || seperator == null || seperator.length() == 0)
            return null;
        ArrayList<String> list = new ArrayList<String>();
        int pos1 = 0;
        int pos2;
        for (;;) {
            pos2 = line.indexOf(seperator, pos1);
            if (pos2 < 0) {
                list.add(line.substring(pos1));
                break;
            }
            list.add(line.substring(pos1, pos2));
            pos1 = pos2 + seperator.length();
        }
        for (int i = list.size() - 1; i >= 0 && list.get(i).length() == 0; --i) {
            list.remove(i);
        }
        return list.toArray(new String[0]);
    }

    public static int convertInt(String str, int defaults) {
        if (str == null) {
            return defaults;
        }
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
            return defaults;
        }
    }
}

Related

  1. splitBySeparatorAndParen(String line, char sep)
  2. splitBySeparatorQuoteAndParen(String line, char sep)
  3. splitCommandLine(String str, boolean extract)
  4. splitCommaSeparated(String line)
  5. splitHiddenNewLine(String s)
  6. splitIntoLines(String str)
  7. splitIntoNonEmptyLines(String s)
  8. splitIntoNonEmptyLinesWithoutNetLogoComments( String s)
  9. splitLine(final String line, final char delimiter, final char qualifier, final int initialSize)