I have a database query that returns some string data in a column. I would like to trim this field based on whether a particular string exists in the data?
If开发者_JAVA百科 the string contains a comma ",", I'm looking to return LEFT of that first comma If the string contains a hypen "-", I would like to return LEFT of that first hypen If the string contains neither, I would like to return the first 14 characters of the string?
I am headed in this direction at the moment:
StringHandling.LEFT(row1.DESCRIPTION,StringHandling.INDEX(row1.DESCRIPTION,"-"))
How can I include some logic to check for the comma or lack thereof and return the appropriate substring in my expression??
Thanks so much!
Another alternative (I stole Bohemian's Math.min() technique ;-)) :
public String dbString(String s){
String[] parts = s.split("(,|-)");
String trimmed = parts.length > 1? parts[0] : parts[0].substring(0, Math.min(14, parts[0].length());
return trimmed;
}
Something like this? (Edited to handle null
)
public static String specialTrim(String input) {
if (input == null)
return null; // or return "", or whatever else you want
if (input.contains(","))
return input.substring(0, input.indexOf(","));
if (input.contains("."))
return input.substring(0, input.indexOf("."));
return input.substring(0, Math.min(14, input.length()));
}
The Math.min()
is to handle when the string is less than 14 characters long.
Check the API for String.contains, String.indexOf, and String.substring.
String theString = <wherever it comes from>;
// if it contains a ,
if (theString.contains(",")) {
// return all elements one position to the left
return theString.substring(0, theString.indexOf(",") - 1);
} else // and repeat
精彩评论