ASHISH12021
BAN USERprivate static String getSmartSubString(String message){
if(message == null){
return "";
}
if(message.length()<=30){
return message;
}
else{
String s30 = message.substring(0, 31);
// take substring upto 31st character in input string
String subStr = message.substring(0, 32);
//check if last char in substring is alphabet or number
if(!isAlphaOrNum(subStr.charAt(31))){
//if not alphabet or number, check if its one of the predefined symbols that are supposed to separate two sentences
if(isSymbol(subStr.charAt(31))){
return subStr.substring(0, 31);
}
}
else{
for(int i = subStr.length()-1; i>=0; i--){
if(isSymbol(subStr.charAt(i))){
return subStr.substring(0, i);
}
}
}
}
return "";
}
private static boolean isAlphaOrNum(char ch){
boolean alpha = (ch <= 'z' && ch >= 'a') || (ch <= 'Z' && ch >= 'A');
boolean num = (ch <= '9' && ch >= '0');
if(alpha || num){
return true;
}
return false;
}
private static boolean isSymbol(char ch){
char[] symbols = {',', '.', ';', '!', ' '};
for(char c : symbols){
if(c == ch){
return true;
}
}
return false;
}
This is java version of the code with sliding window approach. Feel free to add comments on how to optimize this code.
- ASHISH12021 September 17, 2015