Data AccessCore JavaApp FrameworksViewTestingBuildingDeploymentDev ToolsSecurityOpinions

Tuesday, April 14, 2009

Converting Camelcase to SEO friendly strings

Recently, I've been working on a simple code generator that generates code, facilitating CRUD operations on a simple database table. I quickly needed to find a way to turn a CamelCase string into an SEO friendly string, converting a string like, "camelCase" to "camel-case".

Below is a code snippet that does just that. It isn't the most efficient code, but it does get the job done. I've been using this code to generate Struts2, Spring JDBC CRUD code, following conventions dictated by the Struts2 Convention Plugin.

There is a dependency on the commons-lang package, which you will need in your build path to compile:

The code snippet follows:

package com.edwardwebnerd.tools.generator;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.log4j.Logger;

public class StringConverter{

private static final char [] capitalLetters = new char[] {'A','B','C','D','E','F',
'G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

public static String toSearchEngineOptimized(String aString){
ArrayList stringPieces = new ArrayList();
int firstCapital = StringUtils.indexOfAny(aString, capitalLetters);
int tempIndex = 0;

while(firstCapital > 0){
String snippet = aString.substring(tempIndex, firstCapitalIndex);
tempIndex = firstCapital;
stringPieces.add(StringUtils.uncapitalize(snippet));
firstCapital = 
StringUtils.indexOfAny(aString.substring(firstCapital), capitalLetters);

}
stringPieces.add(StringUtils.uncapitalize(aString.substring(tempIndex)));

String foldername = "";
for(int i = 0; i < stringPieces.size(); i++){
if(i == 0)
foldername = stringPieces.get(i);
else
foldername = foldername + "-" + stringPieces.get(i);
}

return foldername;
} 


If you have any questions, please just comment and I'll get back to you.

4 comments: