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;
}
}
Related
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);
}
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;
}
}
}
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();
}
I am very new to programming and I have to write a method and program for the following; public static String repeat(String str, int n) that returns the string repeated n times. Example ("ho", 3) returns "hohoho" Here is my program so far:
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
System.out.println(repeat (str));//Having trouble with this line
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return ""//Having trouble with this line
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
I made some changes to my code, but it still is not working
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
int n = in.nextInt();
System.out.println(repeat(str,n));
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return "";
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
You've missed a semi colon on the line you're having trouble with, it should be return ""; and not return ""
Also, the line System.out.println(repeat (str)); should have 2 arguments because you're repeat definition is:
public static String repeat(String str, int n)
As a further note, an easier function might be
public static String repeat(String str, int n)
{
if (n == 0) return "";
String return_str = "";
for (int i = 0; i < n; i++)
{
return_str += str;
}
return return_str;
}
public static String repeat(String toRepeat, int n){
if(n==0){
return "";
}
return toRepeat+repeat(toRepeat,n-1);
}
2 things I noticed quickly: you forgot a semi-column and your call of "repeat" doesn't match the method signature (you forgot n)
You are not passing correct arguments while you calling the desired method.
Call as repeat (str,k) k - should be an integer
I have to make a program that counts the number of the letter B in a string. I got that part already, but it also requires me to use a static method that returns true or false based on if the string has any Bs in it and i really don't see how to fit that part in.
import java.util.Scanner;
public class CountB {
// write the static method “isThisB” here
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a string: ");
String w = keyboard.nextLine();
int count=0;
for (int i=0; i<w.length(); i++)
{
if (w.charAt(i)=='B'||w.charAt(i)=='b')
{
count++;
}
}
System.out.println("Number of B and b: "+ count);
}
}
private static boolean hasAnyB(String str) {
return str.contains("B") || str.contains("b");
}
Something like this:
static boolean check(String str){
if(str.indexOf('B')>0 || str.indexOf('b')>0 )
return true;
else
return false;
}
Use the built-in matches() method, which uses regex:
private static boolean hasB(String str) {
return str.matches(".*[bB].*");
}
Using regex is a near way to handle mixed case issues.
Just Deploy all coding inside a static method that's it
public static void main(String[] args)
{
methodOne("Pass string over here");
}
public static boolean methodOne(String s)
{
return s.contains("B");
}
To get the count of b or B you can do
int bCount = w.replaceAll("[^Bb]", "").length();
If you have to use a hasB method you could do it like this, though its pretty inefficient and longer than it needs to be
int count = 0;
for(String ch: w.split("")) // one character at a time.
if(hasB(ch))
count++;
private static boolean hasAnyB(String str) {
return str.toLowerCase().contains("b");
}
The easiest i could think.
static boolean isThisB(String s, int count) {
for(int i=0; i<s.lenght(); i++) {
char c = s.charAt(i);
if(c == 'b' || c == 'B')
count ++;
}
return count > 0;
}