When you’re learning Java, one of the common tasks you’ll come across is manipulating strings. In this blog, we’ll walk you through a simple program that removes characters at odd positions from a string. Don’t worry if you’re just starting out—I’ll explain everything step by step!
Understanding the Task
Let’s say you have a string like "Hello World"
, and you want to remove the characters at odd positions. In programming, string indices usually start at 0, so the characters at “odd positions” are those at index 1, 3, 5, and so on. Our goal is to remove these characters and only keep those at even positions.
For example, from "Hello World"
, the program should give us "HloWrd"
.
The Code
Here’s the Java code that accomplishes this task:
import java.util.Scanner;
public class RemoveCharAtOddPosition {
// Method to remove characters at odd positions in the string
public static String removeCharAtOddPosition(String str) {
// Create an empty string to store the result
StringBuilder sb = new StringBuilder();
// Loop through each character in the string
for (int i = 0; i < str.length(); i++) {
// Check if the position is even (0, 2, 4, ...)
if (i % 2 == 0) {
// If the position is even, add the character to the result
sb.append(str.charAt(i));
}
}
// Return the final string with characters at odd positions removed
return sb.toString();
}
// Main method to run the program
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scan = new Scanner(System.in);
// Prompt the user to enter a string
System.out.println("Enter a string:");
String str = scan.nextLine();
// Call the method to remove characters at odd positions
String newString = removeCharAtOddPosition(str);
// Print the result
System.out.println("String after removing characters at odd positions: " + newString);
}
}
Now, let’s break down what each part of the code does.
Code Breakdown
1. Importing the Scanner Class
import java.util.Scanner;
The Scanner
class is used to get user input. In this program, we’ll use it to read the string that the user wants to process.
2. The removeCharAtOddPosition
Method
public static String removeCharAtOddPosition(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (i % 2 == 0) {
sb.append(str.charAt(i));
}
}
return sb.toString();
}
StringBuilder sb = new StringBuilder();
: We useStringBuilder
to build our result string. It’s more efficient than using string concatenation in a loop.- Looping Through the String: The
for
loop goes through each character in the string using the indexi
. - Checking the Index: The
if (i % 2 == 0)
statement checks if the indexi
is even. The%
operator gives the remainder of dividingi
by 2. If the remainder is 0, it meansi
is even, and we keep that character. - Appending to
StringBuilder
: If the index is even, we usesb.append(str.charAt(i));
to add the character at that position to our result string. - Returning the Result: Finally,
sb.toString()
converts theStringBuilder
into a string that we can return.
3. The main
Method
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a string:");
String str = scan.nextLine();
String newString = removeCharAtOddPosition(str);
System.out.println("String after removing characters at odd positions: " + newString);
}
- Reading User Input: The program starts by asking the user to enter a string. The
scan.nextLine()
method reads this input. - Calling the Method: We then call
removeCharAtOddPosition(str)
to process the string and remove the characters at odd positions. - Displaying the Result: Finally, we print out the modified string.
Running the Program
When you run this program, it will ask you to enter a string. After you input the string, the program will output the new string with characters at odd positions removed.
For example:
Enter a string:
Hello World
String after removing characters at odd positions: HloWrd
Summary
In this blog, we learned how to create a simple Java program that removes characters at odd positions in a string. We used basic concepts like loops, conditionals, and string manipulation to achieve this. This exercise is a great way to practice working with strings and understanding how to manipulate them in Java.
Feel free to experiment with different strings and see how the program behaves!