Reversing a String of words with recursion - java

I am trying to reverse a full string in java
For example, Good morning so the output should return morning good.
I am tried the below function
public static String reverse(String s)
{
if (s.isEmpty())
return s;
//int n = 0;
return reverse(s.substring(1)) + s.charAt(0);
}
But the above function is converting good morning into gninrom doog. My code working on each character, how I make it work on words. Any hint or guide/explanation will be appreciated.
I already been to this question but not solving my problem
Updated:
Trying the below code with the help of #snr answer and #NathanHughes comments
public static String reverse(String s)
{
int s1 = s.indexOf(" ");
if (s1 != -1)
{
return reverse(s.substring(s1+1)) + s.substring(0,s1);
}
else
{
return "-1";
}
}
But output is
-1good

At first, you need to know where spaces are.
public static String reverse(String str) {
int space = str.indexOf(" ");
return space == -1 ? str : reverse(str.substring(space + 1)) + " " + str.substring(0, space);
}

This may not be the most efficient way of doing it, but it works:
public static String reverse(String s) {
String[] wordList;
wordList = s.split(" ");
String reverseWordList = "";
for (int i = 1; i <= wordList.length; i++) {
reverseWordList += wordList[wordList.length - i] + " ";
}
reverseWordList = reverseWordList.trim();
return reverseWordList;
}

Related

Convert String to Reverse String Using Recursion in Java

Today I am trying to convert String to reverse String e.g(Cat Is Running into Running Is Cat) word by word not Character
public class ReverseString_ {
public static void reverse(String str) {
String[] a = str.split(" ");
for (int i = a.length - 1; i >= 0; i--) {
System.out.println(a[i] + " ");
}
}
public static void main(String[] args) {
reverse("Cat Is Running");
}
}
The following output is shown:
Running Is Cat BUILD SUCCESSFUL (total time: 0 seconds)
I am trying to convert String into reverse String same as above but through Recursion method but it seems too confusing. and display more errors. Can someone please help me understanding it. Many thanks
public static String reverse_recursion(String str) {
if (str == null)
return null;
else {
String Arry[] = str.split(" ");
int n = Arry.length - 1;
System.out.println(Arry[n] + "");
return reverse_recursion(Arry[n - 1]);
}
}
public static void main(String[] args) {
reverse_recursion("Cat Is Running");
}
This code show following output:
Running
Is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
This code do not print (0) index why? can someone help me to solve this error please
This solution might be helpful. The comments explain the code pretty much.
public static String reverse_recursion(String str) {
String[] arry = str.split(" ", 2); //Split into a maximum of 2 Strings
if (arry.length > 1) { //If there is more than 1 word in arry
//Return the reverse of the rest of the str (arry[1])
//and concatenate together with the first word (arry[0])
return reverse_recursion(arry[1]) + " " + arry[0];
}
return arry[0]; //If less than or equal to 1 word, just return that word
}
This should work:
public static String reverse(String s) {
int idx = s.indexOf(" ");
if (idx < 0) {
// no space char found, thus, s is just a single word, so return just s itself
return s;
} else {
// return at first the recursively reversed rest, followed by a space char and the first extracted word
return reverse(s.substring(idx + 1)) + " " + s.substring(0, idx);
}
}
public static void main(String[] args) {
System.out.println(reverse("Cat Is Running"));
}
You are sending the last element of the Array next time instead of the String without the previously printed String.
Replace your return statement with this it should work.
return reverse_recursion(n==0?null:str.substring(0,(str.length()-Arry[n].length())-1));

Replace words in a string without using replace in Java

I am trying to replace all occurrences of a word in a string. However with this code I can only find the first occurrence of it and replace it. Is there any way to expand this code to replace the words in the entire string? I am attempting to do this without using the replace built in methods in Java since I already know how to use those function, I was wondering if there was another way to go about it.
public static String replace(String old, String newWord, String input) {
int i = input.indexOf(old);
if (i < 0) {
return input;
}
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
return partBefore + newWord + partAfter;
}
First, you need a loop of some kind. Probably a while.
In the loop, since you're replacing the "old" string, you could just keep looping until you don't find it anymore. But if you want to avoid re-searching the first part of the string, or if you want to allow the replacement to contain the string it's replacing (without then looping infinitely), then once you've done each replacement, use String#indexOf(String str, int fromIndex), which lets you continue from the middle of the string.
There is a simple solution that uses recursion. Once you have replaced the word for the first time in the string, you can then replace the word in the partAfter part of the string by calling the replace method again:
public static String replace(String old, String newWord, String input) {
int i = input.indexOf(old);
if (i < 0) {
return input;
}
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
return partBefore + newWord +
replace(old, newWord, partAfter); // <<-- Note recursion here
}
This only changes one line from your original source.
public static String replace(String old, String newWord, String input) {
int i = input.indexOf(old);
if (i < 0) {
return input;
}
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
return partBefore + newWord + replace(old, newWord, partAfter );
}
However, it's more efficient to collect the bits and pieces in a StringBuilder.
public static String replace(String oldStr, String newStr, String input) {
StringBuilder sb = new StringBuilder();
int i;
int prev = 0;
while( (i = input.indexOf(oldStr, prev)) >= 0 ){
sb.append( input.substring(prev, i) ).append( newStr );
prev = i + oldStr.length();
}
sb.append(input.substring(prev));
return sb.toString();
}
First of all, don't use new for a variable name. It's a reserved word.
Second of all, in order to replace multiple occurences, you should have a loop.
Finally, it's better to create the new String using a StringBuilder, not String concatenation.
This is untested, but something like this should work:
public static String replace(String oldStr, String newStr, String input) {
int i = input.indexOf(oldStr);
if (i < 0) {
return input;
}
StringBuilder buffer = new StringBuilder();
int prev = 0;
while (i >= 0) {
String partBefore = input.substring(prev, i);
prev = i + oldStr.length();
buffer.append(partBefore);
buffer.append(newStr);
i = input.indexOf(oldStr, i + oldStr.length());
}
buffer.append(input.substring(i+oldStr.length()));
return buffer.toString();
}
Use Recursion:
public static String replaceAll(String old, String newWord, String input) {
int i = input.indexOf(old);
if (i < 0)
return input;
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
return replaceAll(old, newWord, partBefore + newWord + partAfter);
}
Use do-While and go on replacing words:
public static String replaceAll(String old, String newWord, String input) {
boolean loop = true;
do {
int i = input.indexOf(old);
if (i > 0) {
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
input = partBefore + newWord + partAfter;
} else
loop = false;
} while (loop);
return input;
}
Here is the Code
import java.util.Scanner;
public class replacechar {
String line;
String s = "";
char from ;
char to ;
public replacechar()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter The String");
line = scan.nextLine();
System.out.println("Enter The Character you want to changer");
from = scan.nextLine().charAt(0);
System.out.println("Enter the Character you want to replace with");
to = scan.nextLine().charAt(0);
replacecharacter(from,to);
}
public void replacecharacter(char f,char t)
{
for(int i =0;i< line.length();i++)
{
if(line.charAt(i) == f)
{
s += t;
}
else
{
s += line.charAt(i);
}
}
System.out.println(s);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
replacechar obj = new replacechar();
}
}
Not too sure if OP is still looking for answers but it might help others. Here is my code with just for loop and java's substring method...
public static void main(String ar[])
{
String str = "This is some string. replace lower case is with IS";
String pattern = "is";
String replaceWith = "IS"; // word to replace with
System.out.println(replaceString(str, pattern, replaceWith));
}
static String replaceString(String str, String pattern, String replaceWith) {
String temp = "";
String replacedString = ""; // Replaced String
int remainingString = 0; // append the rest of the string after last
// occurance of pattern.
for (int i = 0; i <= str.length() - pattern.length(); i++) {
temp = str.substring(i, i + 1);
if (str.substring(i, i + pattern.length()).equals(pattern)) {
temp = replaceWith + " ";
i += pattern.length();
}
remainingString = i;
replacedString += temp;
}
replacedString += str.substring(remainingString + 1, str.length());
return replacedString;
}
}
Posting this here incase somebody needs an implementation without using StringUtils helper methods.
static String replaceAll(String str, String oldW, String newW) {
// code here
char[] ch = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ch.length;i++) {
if (ch[i] == oldW.charAt(0) && checkForString(i+1,oldW,str)) {
sb.append(newW);
i += oldW.length() -1;
}
else
sb.append(ch[i]);
}
return sb.toString();
}
static boolean checkForString(int i, String str,String ogStr) {
int start = i;
for (int j = 1; j < str.length() && i < ogStr.length(); j++, i++) {
if (ogStr.charAt(i) != str.charAt(j))
return false;
}
return (i-start+1) == str.length()?true:false;
}

String word reverse in Java giving wrong result?

Here is my code to print string characters reversed in Java without using any API. But it's not working properly. Can anybody help me to correct it?
public static void main(String args[]) {
String input = "I am test";
String result = "";
for (int i = input.length() - 1; i > 0; i--) {
Character c = input.charAt(i);
if (c != ' ') {
result = c + result;
} else {
System.out.println(result + " ");
}
}
}
It is giving output "test amtest", while the output should be "test am I".
Please help me to get exact output without using predefined methods or API's.
There are four problems with your implementation:
You do not go all the way down to zero,
You put an end of line after each printout in the loop,
You do not print the "tail" result after the loop is over, and
You do not clear out result after printing it in the loop.
Fixing these issues will give you proper output (demo).
try
public static void main(String args[]) {
String input = "I am test";
String result = "";
int start=input.length()-1;
for (int i = input.length()-1; i >=0; i--) {
Character c = input.charAt(i);
if (c == ' ') {
for(int j=i+1;j<=start;j++)
result +=input.charAt(j);
result+=" ";
start=i-1;
}
else if (i==0)
{
for(int j=0;j<=start;j++)
result +=input.charAt(j);
}
}
System.out.println(result);
}//It is giving output as test amtest
//output should be : test am I
public static void main(String args[]) {
String input = "I am test";
String result = "";
String[] frags = input.split(" ");
for (int i = frags.length - 1; i >= 0; i--) {
System.out.print(frags[i] + " ");
}
System.out.println();
}
You can try recursion as well -
public static void main(String args[]) {
String input = "I am test";
List<String> listOfString = Arrays.asList(input.split(" "));
System.out.println(reverseString(listOfString));
}
private static String reverseString(List<String> input) {
int n = input.size();
String result = "";
if(input.isEmpty()){
return result;
}
if(n>1){
/*adding last element with space and changes the size of list as well
test + " " + [am, I]
test + " " + am + " " + [I]*/
result = input.get(n-1) + " " + reverseString(input.subList(0, n-1));
}else{
result = input.get(n-1);
}
return result;
}
hope it helps.
public static void main(String args[]){
String input = "I am test";
String result="";
for(int i=input.length()-1;i>=0;i--){
result=result+input.charAt(i);
}
System.out.println(result);
}

Write a method to replace all spaces in a string with '%20'?

I have a question about a programming problem from the book Cracking The Code Interview by Gayl Laakmann McDowell, 5th Edition.
I'm not sure what is wrong with my answer? It varies a lot from the answer given in the book.
public String replace(String str){
String[] words = str.split(" ");
StringBuffer sentence = new StringBuffer();
for(String w: words){
sentence.append("%20");
sentence.append(w);
}
return sentence.toString();
}
Question in the book says:
Note: if implementing in Java, please use a character array so that
you can perform this operation in place.
It also says that the char array that you get as input is long enough to hold the modified string.
By using split and StringBuffer you use additional O(n) space. That's why your answer varies a lot and is incorrect (apart from adding additional "%20").
In this loop, the program adds %20 before each word:
for(String w: words){
sentence.append("%20");
sentence.append(w);
}
That will produce incorrect results, for example for a b it will give %20a%20b.
There's a much simpler solution:
public String replace(String str) {
return str.replaceAll(" ", "%20");
}
Or, if you really don't want to use .replaceAll, then write like this:
public String replace(String str) {
String[] words = str.split(" ");
StringBuilder sentence = new StringBuilder(words[0]);
for (int i = 1; i < words.length; ++i) {
sentence.append("%20");
sentence.append(words[i]);
}
return sentence.toString();
}
You can also do the following, which replaces any space
String s = "Hello this is a string!";
System.out.println(replaceSpace(s, "%20"));
public static String replaceSpace(String s, String replacement) {
String ret = s.replaceAll(" *", replacement);
return ret;
}
Gives
Hello%20this%20is%20a%20string!
One of the simplest way:
public void replaceAll( String str )
{
String temp = str.trim();
char[] arr = temp.toCharArray();
StringBuffer sb = new StringBuffer();
for( int i = 0; i < arr.length; i++ )
{
if( arr[i] == ' ' )
{
sb.append( "%20" );
}
else
{
sb.append( arr[i] );
}
}
}
private static String applyReplaceOperationWithCount(String str) {
if (StringUtils.isEmpty(str)) { //if string is null or empty, return it
return str;
}
char[] strChar = str.toCharArray();
int count = 0; //count spaces in the string to recalculate the array length
for (char c : strChar) {
if (c == ' ') {
count++;
}
}
if (count == 0) { // if there are no spaces in the string, return it
return str;
}
int length = strChar.length;
char[] newChar = new char[length + (count * 2)]; // 1 char will be replaced by 3 chars. So the new length should be count*2 larger than original
int index = 0;
for (char c : strChar) {
if (c != ' ') { // if char is not a space just push it in the next available location
newChar[index++] = c;
} else { // if char is a space just push %,2,0
newChar[index++] = '%';
newChar[index++] = '2';
newChar[index++] = '0';
}
}
return new String(newChar); // convert the new array into string
}
I am using matches and replaceAll it works well.
public class ReplaceSpaces {
public static void main(String[] args) {
String text = " Abcd olmp thv ";
if(text.matches(".*\\s+.*")){
System.out.println("Yes I see white space and I am replacing it");
String newText = text.replaceAll("\\s+", "%20");
System.out.println(newText);
}
else{
System.out.println("Nope I dont see white spaces");
}
}
}
Output
Yes I see white space and I am replacing it
%20Abcd%20olmp%20thv%20
public static String replaceSpaceInString(String string,String toreplace){
String replacedString = "";
if(string.isEmpty()) return string;
string = string.trim();
if(string.indexOf(" ") == -1)return string;
else{
replacedString = string.replaceAll("\\s+",toreplace);
}
return replacedString;
}

Recursion - Double each char of a string input and cut of the last char afterwards with one method [duplicate]

I have the following problem.
The recursive method public static String doSomeMagic("Test") should return:
TTeesstt
TTeess
TTee
TT
I've implemented this behaviour already like this:
public static String rowFunction(String s) {
String toReturn = new String();
if (!s.isEmpty()) {
toReturn = String.valueOf(s.charAt(0));
toReturn += toReturn + rowFunction(s.substring(1));
}
return toReturn;
}
public static String doSomeMagic(String s) {
String toReturn = new String();
if (!s.isEmpty()) {
toReturn = rowFunction(s) + "\n" + doSomeMagic(s.substring(0, s.length() - 1));
}
return toReturn;
}
How can one achieve this with just one function? Any ideas?
I noticed you wanted to do this without a loop and in one function call. You can probably clean this up a lot more. Here it is:
public static String doSomeMagic(String s) {
if (!s.isEmpty()) {
StringBuffer sb = new StringBuffer();
return sb.append(s.replaceAll("(\\S)", "$1$1"))
.append("\n")
.append(doSomeMagic( s.replaceAll(".$", "") )
.toString();
}
return "";
}
To do it in one function, just iterate over the string rather than calling another recursive function.
public static String doSomeMagic(String s) {
String doubled = new String();
if (s.length() == 0) return s;
for(int i=0;i<s.length();i++)
doubled += s.substring(i,i+1) + s.substring(i,i+1)
return doubled + "\n" + doSomeMagic(s.substring(0, s.length()-1));
}
Quick solution could be like
testMethod(string ip){
if(ip.length()==1){
ip=ip.toUppercase();
}
For(int i=0;i<ip.length()-1;i++){
System.out.print(ip.charAt(i)+""+ip.charAt(i));
}
if(ip.length()>1){
System. out. println();
testMethod(ip.substring(1));
}
}
Haven't tested it... But should work fairly

Categories