Returns a substring until the first carriage return and/or line feed. - Java java.lang

Java examples for java.lang:String Substring

Description

Returns a substring until the first carriage return and/or line feed.

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] argv) {
        String input = "java2s.com";
        System.out.println(chop(input));
    }//from  w  w w.  j  a  v  a2 s  . c o m

    /**
     * Returns a substring until the first carriage return and/or line feed.
     * Used to remove carriage return/line feed from a string.
     * 
     * @param input
     *            Line string
     * @return String
     */
    public static String chop(String input) {
        String array[] = input.split("\r\n|\n|\r");
        return array[0];
    }

    /**
     * Splits an input string into a token list with the use of a delimiter
     * string. Adds empty strings when two delimiters follow immediately after
     * each other.
     * 
     * @param input
     * @param delim
     * @return List of strings
     */
    public static List<String> split(String input, String delim) {
        ArrayList<String> array = new ArrayList<String>();
        StringTokenizer st = new StringTokenizer(input, delim, true);
        String current;
        String last = "";
        while (st.hasMoreElements()) {
            current = st.nextToken();
            if (!current.equals(delim)) {
                array.add(current);
            } else if (last.equals(delim)) {
                array.add("");
            }
            last = current;
        }
        if (last.equals(delim)) {
            array.add("");
        }
        return array;
    }
}

Related Tutorials