I want to reverse a string. input: Computer; This input contains 4 whitespaces in the beginning of the word 'computer'.I want to include these 4 whitespaces in the beginning of the reversed string also.So,the program should include all the whitespaces I put at the beginning while taking the reverse too(I put 4 whitespaces as an example only). output:" retupmoc"; I am attaching my code here.
package BasicTesting;
import java.util.*;
public class Corrected_StringRev {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.nextLine();
String reversed = reverseString( str );
System.out.println( reversed );
}
public static String reverseString( String newString ) {
char ch[]=newString.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev =ch[i];
}
return rev;
}
}
How can I change this code to include the above requirement.Please,rewrite the code.Hope ypu will help.Thanks in adavance!
CodePudding user response:
The logic is simple:
- Traverse the start of the string and add whitespaces to
rev
until you meet the first non-whitespace - Do your string reversal and stop before the whitespace section begins
public static String reverseString(String newString) {
char ch[] = newString.toCharArray();
String rev = "";
int nWhitespace;
for (nWhitespace = 0; nWhitespace < ch.length; nWhitespace ) {
if (!Character.isWhitespace(ch[i]) {
break;
}
rev = ch[i];
}
for(int i = ch.length - 1; i >= nWhitespace; i--){
rev = ch[i];
}
return rev;
}
By the way, you can improve your code by using StringBuilder
instead of =
.
CodePudding user response:
Here instead of keeping a count and then adding it, we will be checking if the character we are at currently in the string is a whitespace character. If yes, we add a space to our string builder.
As soon as we come across a non-whitespace character, we break out of the loop.
strB.append(new StringBuilder(inputString.trim()).reverse().toString());
return strB.toString();
What this code does is:
- Take string inputString and trim it (remove trailing and leading whitespaces.
- Creates a new (anonymous) object of a StringBuilder and reverses it. Convert it into a string to append it to our original StringBuilder strB after the whitespaces. Finally, we convert it into String and return it.
Some tips:
- I will be using StringBuilder as it is mutable so saves space and also it contains a function to reverse it directly.
- You should not call the length function of string in the loop as it will call it for every loop. Better to store the value in a variable and use that variable in the loop.
public static String reverseString(String inputString) {
StringBuilder strB = new StringBuilder();
int len = inputString.length();
for(int i=0;i<len;i ){
if(inputString.charAt(i) == ' '){
strB.append(" ");
}
else
break;
}
strB.append(new StringBuilder(inputString.trim()).reverse().toString());
return strB.toString();
}