Append underscore before each capital letter in the string
We can append any character(like underscore, special characters) before each capital letter in a given string using methods available in Character class, StringBuffer, and StringBuilder.
Example:
Input: KeeplearnersBlogspotCom
Output: _Keeplearners_Blogspot_Com
Program:
public class appendCharacter {
public static void main(String[] args) {
String str = "KeeplearnersBlogspotCom";
String newStr = "";
for (int i = 0; i <= str.length() - 1; i++) {
if (Character.isUpperCase(str.charAt(i))) {
newStr += "_" + str.charAt(i);
//newStr+=str.charAt(i);
} else {
newStr += str.charAt(i);
}
}
System.out.println("append underscore before each capital letter");
System.out.println(newStr);
StringBuffer sb = new StringBuffer();
for (int i = 0; i <= str.length() - 1; i++) {
if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') { // 'A' <= 'ch' <='Z'
sb.append("_");
sb.append(str.charAt(i));
} else {
sb.append(str.charAt(i));
}
}
System.out.println("append underscore before each capital letter using stringbuffer");
System.out.println(sb);
StringBuilder sbu = new StringBuilder();
for (int i = 0; i <= str.length() - 1; i++) {
if ('A' <= str.charAt(i) && str.charAt(i) <= 'Z') {
sbu.append("_");
sbu.append(str.charAt(i));
} else {
sbu.append(str.charAt(i));
}
}
System.out.println("append underscore before each capital letter using stringbuilder");
System.out.println(sbu);
}
}
Output:
Append underscore before each capital letter in string |
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.