Here you can find the source of underscored(String string)
Parameter | Description |
---|---|
string | a parameter |
public static String underscored(String string)
//package com.java2s; /******************************************************************************* * Copyright (c) 2010 Oobium, Inc./* w w w . j a v a2 s.c o m*/ * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Jeremy Dowdall <jeremy@oobium.com> - initial API and implementation ******************************************************************************/ public class Main { /** * Convert from CamelCase to underscored: MyModel -> my_model. * null values are returned as a String -> "null". * All returned characters are lower case. * @param string * @return */ public static String underscored(String string) { return separated(string, '_'); } public static String separated(String string, char separator) { if (string == null || string.length() == 0) { return "null"; } String s = string.trim().replaceAll("[\\s]+", Character.toString(separator)); StringBuilder sb = new StringBuilder(); char[] ca = s.toCharArray(); for (int i = 0; i < ca.length; i++) { if (Character.isUpperCase(ca[i])) { if (i != 0 && Character.isLetterOrDigit(ca[i - 1])) { if (Character.isUpperCase(ca[i - 1])) { if (i < ca.length - 1 && Character.isLetter(ca[i + 1]) && !Character.isUpperCase(ca[i + 1])) { sb.append(separator); } } else { sb.append(separator); } } sb.append(Character.toLowerCase(ca[i])); } else { sb.append(ca[i]); } } return sb.toString(); } }