Get left Most substring by count - Java java.lang

Java examples for java.lang:String Substring

Description

Get left Most substring by count

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String sourceString = "java2s.com";
        int count = 4;
        System.out.println(leftMost(sourceString, count));
    }/*  w w w .  j a v  a2  s .c  o  m*/

    public static String leftMost(String sourceString, int count) {
        String result = "";

        if (!isEmpty(sourceString)) {
            int sourceLen = sourceString.length();
            int targetLen = (sourceLen > count) ? count : sourceLen;

            char[] buffer = new char[targetLen];

            sourceString.getChars(0, targetLen, buffer, 0);
            result = new String(buffer);
        }
        return result;
    }

    public static boolean isEmpty(String str) {
        return (str == null || str.length() == 0);
    }

    public static int length(String source) {
        int result = 0;
        if (isNotEmpty(source)) {
            result = source.length();
        }
        return result;
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }
}

Related Tutorials