Question

Problem 1 Write a class called StringCode with the following functions. (Do not change these function names or return types, else the tests will fail) public static String blowup(String str) Returns a version of the original string as follows: each digit 0-9 that appears in the original string is replaced by that many occurrences of the charakter to the right of the digit. So the string a3tx2z yields attttizzz, and 12x yields 2xxx. A digit not followed by a character (i.e. at the end of the string) is replaced by nothing. public static int maxRun(String str) Given a string, returns the length of the largest run in the string. A run is a series of zero or more adjacent characters that are the same. So the max run of xxyyyz is 3, and the max run of xyz is 1.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Screenshot of output:

un Enter the string: x3tyyyzz Test 1 Result for test l xttttyyyzz Test 2 Result for test 23 BUILD SUCCESSFUL (total time 10 s

Screenshot of code:

import java.util.Scanner; import java. lang. StringBuilder; /Class StringCode public class StringCode public static String bl

//Replace the digit by substır stb.replace(i, i + 1, substr): //Return the string value of stb. return stb.toString) public s

return max; public static void main(Stringl] args]) scanner sc = new scanner (System·in), System.out.println(Enter the strin

Code:

import java.util.Scanner;
import java.lang.StringBuilder;
//Class StringCode
public class StringCode
{
    public static String blowup(String str)
    {
        //stb is used for holding the desired string str.
        StringBuilder stb = new StringBuilder(str);
        //substr is used for the substring which replaces the number in the string as desired.
        String substr = "";
        //getting the ascii value of the characters of str in an array b.
        byte[] b = str.getBytes();
        //The following loop iterates upto the second last character as...
        //there is no need to check the following condition for the last character.
        for(int i = 0; i < str.length()-1; i++)
        {
            //Checking whether there is any number in the string.
            if(b[i] >= 48 && b[i] <= 57)
            {
                //Get the integer value of the number.
                int n = Integer.parseInt(str.substring(i,i+1));
                substr = "";
                //Repeat the next character of the digit for that many times.
                for(int j = 0; j < n; j++)
                {
                    //substr consists of the repiting character.
                    substr += str.substring(i + 1, i + 2);
                }
                //Replace the digit by substr
                stb.replace(i, i + 1, substr);
            }
        }
        //Return the string value of stb.
        return stb.toString();
    }
    public static int maxRun(String str)
    {
        //Default value of count.
        int count, max = 1;
        //The following loop iterates upto the second last character as...
        //there is no need to check the following condition for the last character.
        for(int i = 0; i < str.length()-1; i++)
        {
            count = 1;
            //Compare a character with the next to check the occurrences.
            if(str.charAt(i) == str.charAt(i + 1))
            {
                // Using do-while loop to calculate the length of the run
                do{
                    count++; // Increase count
                    i++; // Move to next character
                }while(i < str.length()-1 && str.charAt(i) == str.charAt(i + 1)); // Checking if the run continues
                if(max < count) // Updating maximum run
                    max = count;
            }
        }
        return max;
    }
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the string:");
        String str = sc.nextLine();
        System.out.println("Test 1");
        String result = blowup(str);
        System.out.println("Result for test 1 = " + result);
        System.out.println("Test 2");
        int num = maxRun(str);
        System.out.println("Result for test 2 = " + num);
     
    }
}

Add a comment
Know the answer?
Add Answer to:
Write a class called StringCode with the following functions. (Do not change these function names or...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Given a string, recursively compress all sets of repeating adjacent chars within an existing string to...

    Given a string, recursively compress all sets of repeating adjacent chars within an existing string to a single char. For example, "XVxzzz" yields "xyz" <pre> ceoveReaeatsl"fffaaac Quuutreturns "far Out" eoveReneatsC"nogoge wogorcriiies") returns "no worries" remaveReneats.C" Tomorrow") returns "Iomeo" s /pre Qparam stc a string of characters @return a version of the original string with all repeating adjacent sequences of the same character, reduced to a single character public static String removeRepeats (String str) { ou are forbidden to use any...

  • JAVA: Run length encoding is a simple form of data compression. It replaces long sequences of...

    JAVA: Run length encoding is a simple form of data compression. It replaces long sequences of a repeated value with one occurrence of the value and a count of how many times to repeat it. This works reasonably well when there are lots of long repeats such as in black and white images. To avoid having to represent non-repeated runs with a count of 1 and the value, a special value is often used to indicate a run and everything...

  • Write a Python function called more() that takes three string inputs and outputs a string Formally,...

    Write a Python function called more() that takes three string inputs and outputs a string Formally, the function signature and output are given by rucharist, char: str words str) > str Use the same names for the input arguments as shown above Note that charl and char2 will always be a string of length 1 (ie, it is a single character. The function checks which of charl or char2 appears more often in the word string and returns that character...

  • Java StringNode Case Study: Rewrite the following methods in the StringNode class shown below. Leave all...

    Java StringNode Case Study: Rewrite the following methods in the StringNode class shown below. Leave all others intact and follow similar guidelines. The methods that need to be changed are in the code below. - Rewrite the indexOf() method. Remove the existing recursive implementation of the method, and replace it with one that uses iteration instead. - Rewrite the isPrefix() method so that it uses iteration. Remove the existing recursive implementation of the method, and replace it with one that...

  • roblem description Write the following functions as prototyped below. Do not alter the function signatures. Demonstrate...

    roblem description Write the following functions as prototyped below. Do not alter the function signatures. Demonstrate each function using literal strings defined in your client program (e.g., don't prompt the user for test inputs) /// Returns a copy of the string with its first character capitalized //I and the rest lowercased /// Example: capitalize("hELLO WORLD") returns "Hello world std::string capitalize(const std::string&str) /// Returns a copy of the string centered in a string of length ·width.. /// Padding is done using...

  • This is Crypto Manager blank public class CryptoManager { private static final char LOWER_BOUND = '...

    This is Crypto Manager blank public class CryptoManager { private static final char LOWER_BOUND = ' '; private static final char UPPER_BOUND = '_'; private static final int RANGE = UPPER_BOUND - LOWER_BOUND + 1; /** * This method determines if a string is within the allowable bounds of ASCII codes * according to the LOWER_BOUND and UPPER_BOUND characters * @param plainText a string to be encrypted, if it is within the allowable bounds * @return true if all characters...

  • Hi, So I have a finished class for the most part aside of the toFile method...

    Hi, So I have a finished class for the most part aside of the toFile method that takes a file absolute path +file name and writes to that file. I'd like to write everything that is in my run method also the toFile method. (They are the last two methods in the class). When I write to the file this is what I get. Instead of the desired That I get to my counsel. I am having trouble writing my...

  • Given the following classes: StringTools.java: public class StringTools { public static String reverse(String s){ char[] original=s.toCharArray();...

    Given the following classes: StringTools.java: public class StringTools { public static String reverse(String s){ char[] original=s.toCharArray(); char[] reverse = new char[original.length]; for(int i =0; i<s.length(); i++){ reverse[i] = original[original.length-1-i]; } return new String(reverse); } /**  * Takes in a string containing a first, middle and last name in that order.  * For example Amith Mamidi Reddy to A. M. Reddy.  * If there are not three words in the string then the method will return null  * @param name in...

  • 1. Write a C++ program called Password that handles encrypting a password. 2. The program must...

    1. Write a C++ program called Password that handles encrypting a password. 2. The program must perform encryption as follows: a. main method i. Ask the user for a password. ii. Sends the password to a boolean function called isValidPassword to check validity. 1. Returns true if password is at least 8 characters long 2. Returns false if it is not at least 8 characters long iii. If isValidPassword functions returns false 1. Print the following error message “The password...

  • Given java code is below, please use it! import java.util.Scanner; public class LA2a {      ...

    Given java code is below, please use it! import java.util.Scanner; public class LA2a {       /**    * Number of digits in a valid value sequence    */    public static final int SEQ_DIGITS = 10;       /**    * Error for an invalid sequence    * (not correct number of characters    * or not made only of digits)    */    public static final String ERR_SEQ = "Invalid sequence";       /**    * Error for...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT