How do you capitalize a char in a string using recursion? - java

I'm currently learning Java recursion for the first time, and am stuck on a problem. The task is to receive a string s and char x, and capitalize the character x if it appears in the string, as well as make all non-x characters lowercase. (i.e. Digging returns diGGinG if x is 'g'). Right now, my code returns "iggingggingGINGINGngg"
I know the code is probably quite flawed, but there aren't many similar recursion problems available and I'm not sure where to start with my mistakes. Any pointers are appreciated.
public class Capitalize {
public static String capitalize(String s, char x) {
if(s.length() == 0) {
return s;
}
String ans = "";
if(s.charAt(0) == x) {
ans += s.substring(1).toUpperCase();
}
else {
ans +=s.substring(1).toLowerCase();
}
return ans + capitalize(s.substring(1), x);
}
public static void main(String[] args) {
System.out.println(capitalize("Digging", 'g')); //return diGGinG
}
}

there is a misunderstanding of the use of substring
System.out.println("Digging".substring(1)); // output : igging
To get the only first element you should use :
System.out.println("Digging".substring(0,1)); // output : D
Try this instead :
public static void main(String []args){
System.out.println(capitalize("Digging", 'g')); // output : diGGinG
}
public static String capitalize(String s, char x) {
if(s.length() == 0) {
return s;
}
String ans = "";
if(s.charAt(0) == x) {
ans += s.substring(0,1).toUpperCase();
}
else {
ans +=s.substring(0,1).toLowerCase();
}
return ans + capitalize(s.substring(1), x);
}

Related

How to print a string letter by letter recursively with a star between each? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need to print a String letter by letter with a * between each letter.
I want to find a recursive solution and not an iterative one. The signature must be :
public static String allStar(String a);
Beshambher's answer is a neat and easy way to do it. But if you want to do it recursively then :
public static String allStar(String a) {
if(a == null || a.isEmpty()) {
return "";
}
if(a.length() == 1) {
return a;
}
return a.charAt(0) + "*" + allStar(a.substring(1));
}
Try this where first the string is split into array of strings of each character and then joined together with a * character in between them.
System.out.println(String.join("*", a.split("")));
try this code :
public class Main {
static String Answer = "" ;
public static void main(String[] args) {
Main.SetStarAfterEachLetter("hello!");
System.out.println(Answer);
}
public static void SetStarAfterEachLetter(String letter){
Answer = Answer + letter.charAt(0);
Answer = Answer + " * ";
letter = letter.substring(1);
if(!letter.isEmpty()) {
SetStarAfterEachLetter(letter);
}
}
}
this is more general answer :
import java.util.Scanner;
public class Main {
static String Answer = "" ;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = scanner.nextLine();
Main.SetStarAfterEachLetter(word);
System.out.println(Answer);
}
public static void SetStarAfterEachLetter(String letter){
Answer = Answer + letter.charAt(0);
Answer = Answer + " * ";
letter = letter.substring(1);
if(!letter.isEmpty()) {
SetStarAfterEachLetter(letter);
}
}
Example implementation using overloaded functions addStar(String str) and addStar(int pos, String str):
public static String addStar(String str) {
if (null == str || str.isEmpty()) {
return str;
}
return addStar(0, str);
}
static String addStar(int pos, String str) {
if (pos == str.length() - 1) {
return Character.toString(str.charAt(pos));
}
return str.charAt(pos) + "*" + addStar(pos + 1, str);
}
Tests
System.out.println(addStar(null));
System.out.println("'" + addStar("") + "'");
System.out.println(addStar("a"));
System.out.println(addStar("ab"));
System.out.println(addStar("abcd"));
Output
null
''
a
a*b
a*b*c*d
Solution for recursive print a string
public static void allStar(String a) {
if (a != null && !a.isEmpty()) {
System.out.print(a.charAt(0));
if (a.length() > 1) {
System.out.print('*');
allStar(a.substring(1));
}
}
}
Solution for recursive build a string
public static void allStar(String a, StringBuilder builder) {
if (a != null && !a.isEmpty()) {
builder.append(a.charAt(0));
if (a.length() > 1) {
builder.append('*');
allStar(a.substring(1), builder);
}
}
}
For reducing heap pollution, this one is the best for recursive string build
public static void allStar(String a, int position, StringBuilder builder) {
if (a != null && position < a.length()) {
builder.append(a.charAt(position));
if (++position < a.length()) builder.append('*');
allStar(a, position, builder);
}
}
Use this for print recursivly builded string
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
allStar("test", 0, builder);
System.out.print(builder);
}
Solution with recursions not recommended, but possible for this task.
class AllStar {
public static String allStar(String a){
return allStar(0, a, "");
}
public static String allStar(int ch, String a, String res){
if(a.length() == 0){
return res;
}
if(ch == a.length() - 1){
res += a.charAt(ch);
return res;
}
else{
res += a.charAt(ch) + "*";
return allStar(ch + 1,a,res);
}
}
public static void main(String args[]){
System.out.println(allStar("aritro"));
}
}
Explanation :
We pass in the starting character index in the ch argument. a takes in the String which is to be printed according to the specified format, i.e., with stars. res takes in the String where the result should be stored. The if-statement checks if the letter is the last one. If true, it just appends the letter without a star to the res String as it is specified that stars should be between letters. It also returns the formatted String stored in res. If it is not the last letter, ch is incremented, the original String is passed as it is, and the formatted String is passed on as well. This continues till the last character is reached.

Use recursive method to prints a string with every second character removed

I want to remove every second character from a string using the recursive method.
public static void main(String[] args) {
System.out.println(everySecond("wonderful"));
}
public static String everySecond(String s) {
if (s.length() % 2 != 0 ) {
System.out.print(s.substring(0,1));
}
if (s.length() <= 1) {
return s;
}
else {
String simpler = everySecond(s.substring(1))+ s.charAt(0);
return "";
}
}
}
Currently the program does what I need.
However, I want to include everything in the sub-recursive call String simpler = everySecond(s.substring(1))+ s.charAt(0); return ""; and remove code below.
if (s.length() % 2 != 0 ) {
System.out.print(s.substring(0,1));
}
I am fairly new to Java so I apologize if the answer is obvious. I assume I am overlooking some very basic solution here.
If the remaining length of the String is < 2 then we don't need to find any more characters to skip over. Otherwise, we need the initial character and then the rest of the String after the second character(the skipped one), therefore I did it like this:
public static String removeEverySecondChar(String str) {
if(str.length() < 2) {
return str;
}
return str.substring(0,1) + removeEverySecondChar(str.substring(2));
}
Input: Wonderful
Output: Wnefl

Recursively reverse string Java

I tried to recursively reverse a string in Java, but I am getting just the last character as output.
I looked up online and most of the codes have modified the input string. I am trying to build the output from empty string to reversed string. Please tell me what is wrong in my program.
class reverseStringRecursion
{
public static void main(String args[])
{
System.out.println(reverse());
}
public static String reverse()
{
String strInput = " Hello I am my name.";
String output = "";
return recursiveHelper(strInput, 0, output);
}
public static String recursiveHelper(String strInput, int index, String output)
{
if(index == (strInput.length() - 1 ))
output += strInput.charAt(index) + "";
else
output+= recursiveHelper(strInput, index + 1, output) +"";
return output;
}
}
The above code is returning output '.' only and nothing else. PLease help.
Others have done a good job of explaining why your code doesn't work. For comparison, here's a working version with some comments:
public static void main(String args[])
{
System.out.println(reverse("Hello I am my name."));
}
public static String reverse(String text)
{
// Base case:
// If the string is empty, we're done.
if (text.length() == 0) {
return "";
} else {
// reverse("hello") = reverse("ello") + "h"
return reverse(text.substring(1)) + text.charAt(0);
}
}
Since String in Java are immuatable, passing it by parameter is useless on this case, so I removed it.
public class Main {
public static void main(String args[]) {
System.out.println(reverse());
}
public static String reverse() {
String strInput = " Hello I am my name.";
return recursiveHelper(strInput, 0);
}
public static String recursiveHelper(String strInput, int index) {
String output;
if(index == (strInput.length() - 1 )){
output = strInput.charAt(index) + "";
}else{
output = recursiveHelper(strInput, index + 1) + strInput.charAt(index);
}
return output;
}
}
Try it online!
Since strInput always contains the original String, the following condition makes sure your code only takes the last character of that String and ignore all the other characters:
if(index == (strInput.length() - 1 ))
output += strInput.charAt(index) + "";
To build the reversed String recursively, you have to append the last character of the String to the reverse of the sub-string of the first length()-1 characters.
This means that you don't need the 2nd and 3rd arguments of your method, and strInput should be passed a shorter String in each recursive call.
public static String reverse (String strInput)
{
if(strInput.length() <= 1)
return strInput;
else
return strInput.charAt(strInput.length()-1) + reverse (strInput.substring(0,strInput.length()-1));
}
I would change your function recursiveHelper() to only receive one argument (the String that you want to reverse). Using the substring method from Java you can do it like this:
public static String recursiveHelper(String strInput) {
if(strInput.length() == 1) {
return strInput;
}
else if(strInput == "") {
return "";
}
String subString1 = recursiveHelper(strInput.substring(0, strInput.length()/2)); // Here we copy the first half of the String to another String
String subString2 = recursiveHelper(strInput.substring(strInput.length()/2)); // Here we do the same, but with the second half of the original String
return susbString2 + subString1; // It is very important that you sum the two substrings in this order!
}
Modified your class:
public class ReverseStringRecursion {
public static void main(String args[])
{
System.out.println(reverse());
}
public static String reverse()
{
String strInput = "My Name is Jane Doe";
String output = "";
return recursiveHelper(strInput,0);
}
public static String recursiveHelper(String strInput, int index)
{
if(index == (strInput.length() - 1 ))
return "" + strInput.charAt(index) ;
else
return recursiveHelper(strInput,index+1) + strInput.charAt(index);
}
}
public class Main
{
public static void main(String[] args) {
String str1="abc";
String str2="";
for(int i=str1.length()-1;i>=0;i--)
{
str2=str2+Character.toString(str1.charAt(i));
}
System.out.println("After Reverse: "+str2);
}
}
1) Base case
if left>=right - do nothing
2) otherwise swap s[left] and s[right} and call helper(left+1, right-1)].
class Solution {
public void reverseString(char[] s) {
int left = 0, right = s.length - 1;
while (left < right) {
char tmp = s[left];
s[left++] = s[right];
s[right--] = tmp;
}
}
}

Inserting phrases before/after certain letters in strings

Hey I'm having another problem with my coding assignment tonight. I'm supposed to write a method to add "bool" in front of every "a" in the passed string s. But my code only adds it to one specific "a". How would a go about fixing this with a while loop. Thanks!
Lets say s=banana
public static String insertBool(String s){
int pos=s.indexOf("a");
if(pos>-1){
String firstS=(s.substring(0,pos));
String secondS=(s.substring(pos, s.length()));
return(firstS+"bool"+secondS);
}
else
return s;
}
You could just replace all the a's in the string with "boola".
public static String insertBool(String s) {
return s.replaceAll("a", "boola");
}
You could use String.replace()
public static String insertBool(String s) {
if (s == null) {
return null;
}
return s.replace("a", "boola");
}
Or you could use a more complicated while and something like,
public static String insertBool(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
int i = 0;
char[] arr = s.toCharArray();
while (i < arr.length) {
if (arr[i] == 'a') {
sb.append("bool");
}
sb.append(arr[i]);
i++;
}
return sb.toString();
}

Recursive String Parser

I need to create a program that recursively parses a string into smaller substrings. Every substring is one letter shorter than the previous; once it's at the end it would redisplay the word, but with the first letter sliced off, and then substrings of that.
For example: Given the word 'Slugger' the program would display
Slugger
Slugge
Slugg
Slug
Slu
Sl
S
lugger
lugge
lugg
lug
lu
l
And on and on.
This is part of my code so far that is supposed to break things up:
private static void stringParser(String str)
{
if(str.length() < 1)
{
return;
}
else if(str.length() == 0)
{
removeFirstChar(str, 1);
}
else
{
System.out.println(str);
stringParser(str.substring(0, str.length() - 1));
}
} // End stringParser method
private static void removeFirstChar(String str, int i)
{
String strNew = str.substring(i);
stringParser(strNew);
return strNew;
} // End removeFirstChar method
I think I've got all the pieces and parts that I need, but perhaps just don't have them in the right order to do what I want.
Any help is greatly appreciated.
Thank you!
I have added the following in your code. See if this works
public static void main(String[] args) {
String str = "slugger";
for(int i=0;i<str.length();i++) {
stringParser(str.substring(i));
}
}
Complete code.....
public class Test {
public static void main(String[] args) {
String str = "slugger";
for(int i=0;i<str.length();i++) {
stringParser(str.substring(i));
}
}
private static void stringParser(String str)
{
if(str.length() < 1)
{
return;
}
else if(str.length() == 0)
{
removeFirstChar(str, 1);
}
else
{
System.out.println(str);
stringParser(str.substring(0, str.length() - 1));
}
} // End stringParser method
private static void removeFirstChar(String str, int i)
{
String strNew = str.substring(i);
stringParser(strNew);
str = strNew;
}
}

Categories

Resources