Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we add an underscore before each capital letter inside a java String?
In this article, we will learn how to add an underscore before each capital letter in a Java String. We also call this process as "camel case to snake case" conversion.
We can solve this problem using the following ways:
Using StringBuffer class
We will use the method called append() of the StringBuffer class to add an underscore.
In this method, we will traverse through each character of the string and check if it is an uppercase letter. If it is, we will append an underscore before it. We will also convert the uppercase letter to lowercase.
Let's look at the steps:
- Initiate a for loop with i = 0 and run it until i is less than the string length.
- Use charAt() method to get the character at the current index.
- Check if the character is an uppercase letter using the isUpperCase() method.
- If it is, append an underscore before it and convert it to lowercase.
- If it is not, append the character as it is.
Example
Following is the Java program to add an underscore before each capital letter in a string using the StringBuffer class:
public class AddUnderScore{
public static void main(String args[]){
String str = "Hello World";
StringBuffer sb = new StringBuffer();
for(int i = 0; i < str.length(); i++){
char ch = str.charAt(i);
if(Character.isUpperCase(ch)){
sb.append("_");
sb.append(ch);
}else if(ch == ' '){
continue;
}else{
sb.append(ch);
}
}
System.out.println("String after adding underscore: " + sb.toString());
}
}
Output
Following is the output of the above code:
String after adding underscore: _Hello_World
Using Regular Expressions
We can also use Regular Expressions to add an underscore before each capital letter in a string.
We will use the replaceAll() method of the String class to do this.
In this method, we will use a regular expression to match all the uppercase letters and replace them with an underscore followed by the lowercase letter.
Let's look at the steps:
- Use the replaceAll() method of the String class.
- Pass the regular expression (?<!^)(?=[A-Z]) as the first argument.
- Pass the replacement string "_$0" as the second argument.
Example
Following is the Java program to add an underscore before each capital letter in a string using Regular Expressions:
import java.util.regex.*;
public class AddUnderScore{
public static void main(String args[]){
String str = "HelloWorld";
String result = str.replaceAll("(?<!^)(?=[A-Z])", "_$0");
System.out.println("String after adding underscore: " + result);
}
}
Output
Following is the output of the above code:
String after adding underscore: _Hello_World