'In this sentence reversal program, why has char been used and not String? [closed]
I was doing a few beginner coding challenges and one of the challenge was making a program that reverses a given String. It worked on words, but as soon as I put in words with spaces between them the program only reversed the first word entered.
I googled "reverse words with spaces in it java" and found this:
// Java program to reverse a string
// preserving spaces.
public class ReverseStringPreserveSpace {
// Function to reverse the string
// and preserve the space position
static void reverses(String str)
{
char[] inputArray = str.toCharArray();
char[] result = new char[inputArray.length];
// Mark spaces in result
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] == ' ') {
result[i] = ' ';
}
}
// Traverse input string from beginning
// and put characters in result from end
int j = result.length - 1;
for (int i = 0; i < inputArray.length; i++) {
// Ignore spaces in input string
if (inputArray[i] != ' ') {
// ignore spaces in result.
if (result[j] == ' ') {
j--;
}
result[j] = inputArray[i];
j--;
}
}
System.out.println(String.valueOf(result));
}
// driver function
public static void main(String[] args)
{
reverses("internship at geeks for geeks");
}
}
Why were char arrays used instead of String directly?
Can I modify my own code to make it reverse a sentence without following the above code? My code:
import java.util.Scanner;
class ReverseString
{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the word to be reversed:");
String input = s.next();
String reversed = "";
for (int i = 0; i < input.length(); i++)
{
char ch = input.charAt(i);
reversed = ch + reversed;
}
System.out.println(reversed);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
