简体   繁体   中英

How to Convert Upper case string to Camel Case and keeping the Acronyms as it is?

I am working on H2 DB and trying to create a Java function to convert Uppercase Strings into Camelcase for my dataset. Although, I am relatively a newbie in JAVA, but after some research I was able to arrive at the solution below.

DROP ALIAS toCamelCase if exists;
CREATE ALIAS toCamelCase AS $$
String toCamelCase(String s)
{ 
   String[] parts = s.split("\\s+");
   String camelCaseString = "";
   for (String part : parts)
   {
      if(part != null && part.trim() != "")
      {
        camelCaseString = camelCaseString + part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase() + " ";
      }
   }
   return camelCaseString;
} $$;

Now this does solve 95 percent of my problem, but the issue is that there are some elements in the dataset which are acronyms or short forms, for eg: FTE or TBB which as a result of this code are being transformed into Fte or Tbb . Can I achieve the same result but this time keeping the acronyms or short forms in their original form for the strings of data I am working on?

Appreciate the help!

If you want to prevent acronyms from being changed, create a separate .txt file with a list on known acronyms. Then you can prevent it from being changed by simply doing this:

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null){
        if (part == line)
            break;
        else
            camelCaseString = camelCaseString + part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase() + " ";
    }
}

Replace this to be the contents of the for each loop.

Remember to set "file" to a File object that contains the .txt file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM