ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized. (Privacy Policy)
    CloudflareThis is used to quickly and efficiently deliver files such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisements has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)