ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to Find the Length of a String in Java

Updated on December 14, 2012

JAVA is a popular programming language developed at Sun Micro-systems by James Gosling in 1995.

JAVA code are compiled into byte code classes, which can run on any machine with JVM installed, irrespective of the Operating System. So, it's also called write once run anywhere programs.

JAVA gives you many predefined collections and functions which makes the life of a programmer easy.

The JVM is smart and runs the byte class as a program, and automatically does memory management using the Garbage collector.

The current version of Java is 1.7 and has lot many useful features such as functions to handle Resource Leaks and enhanced File I/O system.

I have listed down here the code snippet which handles most of the basic string functions, listed below:

  • Check for Null String
  • Check for String Length if not Null
  • Get Name and return List with First,Last and Middle name.
  • Remove prefix suffix and special chars from name
  • Replace patterns in a given String
  • Get Boolean value given a string value of true or false
  • Convert String to Integer
  • Convert Null to Empty string
  • Substring operation
  • Get Formatted SSN
  • Pad, Prepad and postpad strings
  • Converted String separated by a delim into ArrayList
  • Check for string containing only digits



String Utility Code snippet

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author mr-veg
 *
 */
public class StringUtils {
	

	/**
	 * Checks if a string is empty - null strings, "", and "  " are considered empty.
	 *
	 * @param string A String value.
	 *
	 * @return A boolean <code>true</code> if the String is empty,
	 * otherwise <code>false</code>.
	 */

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

	/**
		 * Checks if a string is empty, returns the length if not empty or else returns 0.
		 *
		 * @param string A String value.
		 *
		 * @return Length value or 0 if String is empty.
		 */
	public int getLength(String string) {
		if (isEmpty(string)){
			return 0;
		} else {
			return string.length();
					
		}
	}	

	/**
	 * Returns a List containing the first, middle, and last name given the name
	 * passed to it.
	 * @param name A customer name.
	 * @return A list containing the first, middle, and last name, or null.
	 */
	public List getFirstMiddleLast(String name) {
		if (name==null) return null;
		List nameList = new ArrayList();
		String cleanFullName = cleanName(name);
		if (isEmpty(cleanFullName)) return null;
		String middle = "", last = "";
		try{
			if(cleanFullName.indexOf(" ") == -1){
				nameList.add(0,cleanFullName);
			}else {
				String restOfName = cleanFullName.substring(cleanFullName.indexOf(" ")+1, cleanFullName.length());			
				if (!isEmpty(restOfName) && restOfName.indexOf(" ")>=1) {
					middle = restOfName.substring(0, restOfName.indexOf(" "));
					last = restOfName.substring(restOfName.indexOf(" ")+1, restOfName.length());
				} else {
					last = restOfName;
				}
				nameList.add(0, cleanFullName.substring(0, cleanFullName.indexOf(" ")));
			}
		}catch(Exception ex){
			System.out.println("Exception while trying to parse a name for first middle and last."+ex);
		}
		nameList.add(1, middle);
		nameList.add(2, last);
		return nameList;
	}

	/**
	 * Utility method that removes any prefix, suffix or other special characters
	 * from the full name off of the C+ name struct.
	 * @param name
	 * @return
	 */
	public String cleanName(String name) {
		if (isEmpty(name)) return "";

        // remove '+', '&', and '.' if exists
        name = name.replaceAll("\+", "");
        name = name.replaceAll("\&", "");
        name = name.replaceAll("\.", "");

        String outputName = "";
        List remove = Arrays.asList(new String[]{"MR", "MRS", "MS", "I", "II", "III", "IV", "JR", "SR"});
        StringTokenizer st = new StringTokenizer(name);

        while (st.hasMoreTokens()){
            String token = st.nextToken();
            if (!remove.contains(token))
                outputName = outputName + token + " ";
        }
        return outputName.trim();
    }

	public String replace(String regExpr, String inputStr, String replaceStr) {
		if (isEmpty(regExpr) || isEmpty(inputStr)) return "";
		if (replaceStr==null) replaceStr = "";
		Pattern pattern = Pattern.compile(regExpr);
		Matcher matcher = pattern.matcher(inputStr);
		return matcher.replaceAll(replaceStr);
	}

	public boolean getBooleanValue (String booleanString) {
		boolean boolValue = false;
        if(booleanString != null && booleanString.trim().length() != 0) {
        	try {
        		boolValue = (new Boolean(booleanString)).booleanValue();
        	}
        	catch (Exception e) {}
        }
        return boolValue;
	}

	/**
	 * Converts a String into an integer. If an exception occurs,
	 * zero is returned.
	 * @param intStr
	 * @return
	 */
   	public int convertStringToInt(String intStr) {
   		try {
   	   		return Integer.parseInt(intStr);
   		} catch(NumberFormatException ex) {
   			return 0;
   		}
   	}

	public String nullToEmpty(String inputStr) {		
		if(inputStr == "null")			
			return "";		
		return inputStr.trim();
	}

	public String subString(String strInput, int startIndex, int endIndex) {
		try{
			return strInput.substring(startIndex, endIndex);
		}catch(Exception e) {
			return "";
		}
	}

	public String getFormattedSSN(String inputSSN) {
		if(isEmpty(inputSSN))
			return "";
		String formattedSSN = inputSSN;
		try{
			if(inputSSN.charAt(3) == '-') {
				formattedSSN = subString(inputSSN,0,3) + subString(inputSSN,4,6);
			}
			if(inputSSN.charAt(6) == '-') {
				formattedSSN += subString(inputSSN,7,inputSSN.length());
			}
		}catch(Exception e) {
		}
		return formattedSSN;
	}

	public String prePad(String inputStr, char paddingChar, int length) {
		if(isEmpty(inputStr))
			return inputStr;
		StringBuffer outputStr = new StringBuffer(inputStr);
		try{
			if(inputStr.length() < length) {
				int padLength = length - inputStr.length();
				outputStr = new StringBuffer();
				for(int p=0; p<padLength; p++) {
					outputStr.append(paddingChar);
				}
				outputStr.append(inputStr);
			}
		}catch(Exception e) {

		}
		return outputStr.toString();
	}

	//For Velocity Formatting

	public String pad(String padChar, int length) {
		char paddingChar = padChar.charAt(0);
		StringBuffer outputStr = new StringBuffer();
		for(int p=0; p<length; p++) {
			outputStr.append(paddingChar);
		}
		return outputStr.toString();
	}

	public String prePad(String inputStr, String padChar, int length) {
		char paddingChar = padChar.charAt(0);
		if(isEmpty(inputStr))
			inputStr = " ";
		StringBuffer outputStr = new StringBuffer(inputStr);
		if(inputStr.length() < length) {
			int padLength = length - inputStr.length();
			outputStr = new StringBuffer();
			for(int p=0; p<padLength; p++) {
				outputStr.append(paddingChar);
			}
			outputStr.append(inputStr);
		}
		return outputStr.toString();
	}

	public String postPad(String inputStr, String padChar, int length) {
		char paddingChar = padChar.charAt(0);
		if(isEmpty(inputStr))
			inputStr = " ";
		StringBuffer outputStr = new StringBuffer(inputStr);
		if(inputStr.length() < length) {
			int padLength = length - inputStr.length();
			for(int p=0; p<padLength; p++) {
				outputStr.append(paddingChar);
			}
		}
		return outputStr.toString();
	}

	/**
	 * Converts a string delimited by 'delim' to an ArrayList
	 * @param str
	 * @param delim
	 * @return
	 */
	public ArrayList convertStringToList(String str, String delim) {
		ArrayList list = new ArrayList();
		try {
			StringTokenizer tokenizer = new StringTokenizer(str, delim);
			while(tokenizer!=null && tokenizer.hasMoreTokens()) {
				list.add(tokenizer.nextToken());
			}			
		} catch (Exception ex) {
			System.out.println("Exception while trying to convert String to List."+ ex);
		}
		return list;
	}
		
	/**
	 * Checks if a string only contains digits and no alpha characters.
	 * @param str
	 * @return
	 */
	public boolean containsOnlyDigits(String str) {
		if (isEmpty(str)) return false;
		for (int i=0; i<str.length(); i++) {			
		    if (!Character.isDigit(str.charAt(i))) return false;
		}
		return true;
	}	

	/**
	 * Removes all text before the character value passed in.  
	 * All text after the character is returned as the result.
	 * @param str
	 * @param character
	 * @return
	 */
	public String subString(String str, char character) {
		if (isEmpty(str)) return "";
		String newStr = "";
		try {
			newStr = str.substring(str.indexOf(character)+1);
		} catch (Exception ex) {
			System.out.println("Exception trying to parse string: " + str);
		}
		return newStr;			
	}
	
		
	public static void main(String args[]){
		StringUtils strUtils = new StringUtils();
		System.out.println("***Output***");
		if(strUtils.isEmpty("")) System.out.println("String is Empty, Please enter some value");		
		System.out.println(strUtils.getFirstMiddleLast("God is Love"));
	System.out.println(strUtils.cleanName("MR VEG"));
		System.out.println(strUtils.replace("develop","developer","test"));
		System.out.println(strUtils.getBooleanValue("test"));
		System.out.println(strUtils.convertStringToInt("12"));
		System.out.println("Null to Empty a String: "+strUtils.nullToEmpty("null"));
		System.out.println(strUtils.subString("developer",0,3));
		System.out.println(strUtils.getFormattedSSN("dev-el-oper"));
		System.out.println(strUtils.prePad("sample",'*',9));
		System.out.println(strUtils.pad("code",3));
		System.out.println(strUtils.prePad("sample","s",8));
		System.out.println(strUtils.postPad("sample","%",10));
		System.out.println(strUtils.convertStringToList("I-am-a-S/W-Prof","-"));
		System.out.println(strUtils.containsOnlyDigits("add"));
		System.out.println(strUtils.containsOnlyDigits("1234"));
		System.out.println(strUtils.subString("example",'e'));				
	}
}

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article