Java examples for java.lang:String Substring
Get first name from name
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/sam/trunk/component/src/java/org/sakaiproject/tool/assessment/util/StringParseUtils.java $ * $Id: StringParseUtils.java 9273 2006-05-10 22:34:28Z daisyf@stanford.edu $ *********************************************************************************** * * Copyright (c) 2005, 2006, 2007, 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * 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./*w w w .j a v a2 s . c o m*/ * **********************************************************************************/ //package com.java2s; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { public static void main(String[] argv) { String name = "Abnd Def"; System.out.println(getFirstNameFromName(name)); } /** * utility. * @param name full name * @return (hopefully) first name */ public static String getFirstNameFromName(String name) { String[] names = getNameArray(name); if (names.length == 0) { return ""; } else if (names.length == 1) { return names[0]; } String[] tempNames = new String[names.length - 1]; System.arraycopy(names, 0, tempNames, 0, tempNames.length); names = tempNames; StringBuilder buf = new StringBuilder(); for (int i = 0; i < names.length; i++) { if (names[i].length() > 0) { if (Character.isLowerCase(names[i].charAt(0))) { break; } buf.append(names[i] + " "); } // ifnames } //for String s = buf.toString(); s = s.trim(); return s; } /** * util * @param name * @return each word in name */ private static String[] getNameArray(String name) { ArrayList list = new ArrayList(); StringTokenizer st = new StringTokenizer(name, " "); while (st.hasMoreElements()) { list.add(st.nextToken()); } int size = list.size(); String sa[] = new String[size]; for (int i = 0; i < size; i++) { sa[i] = (String) list.get(i); } return sa; } }