Question

In Java Only can use class String length charAt class StringBuilder length charAt append toString class...

In Java

Only can use

  • class String
    • length
    • charAt
  • class StringBuilder
    • length
    • charAt
    • append
    • toString
  • class Character
    • any method

Create the following methods

  1. nthWord takes an int and a String as input and returns a String:
    The input int represents a number n that is assumed to be positive, and the output string contains every nth word of the input string, starting with the first word, separated by a single space. {\em For this method, a word is defined to be a sequence of non-space characters.} There should be no space at the end of the output string.

    > HW2.nthWord(3, "zero one    two  three four five six seven")
    "zero three six"
    
  2. truncateAfter takes an int and a String as input and returns a String:
    The input string may contain hyphens and spaces that mark appropriate places to truncate the string. The output string will be a truncated version of the input string, and the input int value is the desired length of the output string. The output string should truncate the input string at the first legal spot such that the output string will have at least the desired length. If the truncation happens at a space, the space is not included in the output, but if the truncation happens at a hyphen, the hyphen is included. No other hyphens are included in the output, but the other spaces are. (If the input string does not have enough characters to meet the desired minimum, then the output should be the entire input string without the hyphens.)

    > HW2.truncateAfter(5, "La-te-ly the-re.")
    "Late-"
    > HW2.truncateAfter(6, "La-te-ly the-re.")
    "Lately"
    > HW2.truncateAfter(7, "La-te-ly the-re.")
    "Lately the-"
    
  3. truncateBefore: the same as the truncateAfter method, but now the input int value is the maximum, and the string should be truncated at the latest possible point such that the resulting string has no more than the desired length.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
public static String nthWord(int n, String sentence) {

    StringBuffer buffer = new StringBuffer();

    String[] words = sentence.split("\\s+");
    int currentIndex = 0;
    while (currentIndex < words.length) {
        buffer.append(words[currentIndex]).append(" ");
        currentIndex += n;
    }
    return buffer.toString().trim();
}

===================================================================================

public static String truncateAfter(int n, String phrase) {

    StringBuffer buffer = new StringBuffer();
    int index = 0;
    int m = n;
    while (n > 1) {
        if (('a' <= phrase.charAt(index) && phrase.charAt(index) <= 'z') ||
                ('A' <= phrase.charAt(index) && phrase.charAt(index) <= 'Z') ||
                ' ' == phrase.charAt(index)) {
            buffer.append(phrase.charAt(index));
            n -= 1;
        }
        index += 1;
    }
    if (phrase.charAt(m) == '-') {
        buffer.append('-');

    } else if (phrase.charAt(index) != ' ') {
        buffer.append(phrase.charAt(index));
    } else {
        while (true) {
            buffer.append(phrase.charAt(index));
            index++;
            if (phrase.charAt(index) == '-') {
                break;
            }
        }
         buffer.append('-').toString();
    }
    return buffer.toString();

}

==============================================================================

public static String truncateBefore(int n, String phrase) {

    StringBuffer buffer = new StringBuffer();
    int index = 0;
    int m = n;
    while (n > 1) {
        if (('a' <= phrase.charAt(index) && phrase.charAt(index) <= 'z') ||
                ('A' <= phrase.charAt(index) && phrase.charAt(index) <= 'Z') ||
                ' ' == phrase.charAt(index)) {
            buffer.append(phrase.charAt(index));
            n -= 1;
        }
        index += 1;
    }
    if (phrase.charAt(m) == '-') {
        buffer.append('-');

    } else if (phrase.charAt(index) != ' ') {
        buffer.append(phrase.charAt(index));
    }
    return buffer.toString();
}
Add a comment
Know the answer?
Add Answer to:
In Java Only can use class String length charAt class StringBuilder length charAt append toString class...
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
  • In Java All methods listed below must be public and static. If your code is using...

    In Java All methods listed below must be public and static. If your code is using a loop to modify or create a string, you need to use the StringBuilder class from the API. Keep the loops simple but also efficient. Remember that you want each loop to do only one "task" while also avoiding unnecessary traversals of the data. No additional methods are needed. However, you may write additional private helper methods, but you still need to have efficient...

  • language is java Restrictions: You are not allowed to use anything from the String, StringBuilder, or...

    language is java Restrictions: You are not allowed to use anything from the String, StringBuilder, or Wrapper classes. In general, you may not use anything from any other Java classes, unless otherwise specified. You are not allowed to use String literals in your code ("this is a string literal"). You are not allowed to use String objects in your code. The methods must be implemented by manipulating the data field array, The CSString Class: NOTE: Pay very careful attention to...

  • Programming project in Java: You are allowed to use the following methods from the Java API:...

    Programming project in Java: You are allowed to use the following methods from the Java API: class String length charAt class StringBuilder length charAt append toString class Character any method Create a class called HW2 that contains the following methods: 1. isAlphabeticalOrder takes a String as input and returns a boolean: The method returns true if all the letters of the input string are in alphabetical order, regardless of case. The method returns false otherwise. Do not use arrays to...

  • Topics: About Java What is a compiler, and what does it do? Characteristics of the languageStrongly...

    Topics: About Java What is a compiler, and what does it do? Characteristics of the languageStrongly typed and statically typed Everything has a data type & data types must be declared Case sensitive Object oriented System.out.print() vs. System.out.println() How to use the Scanner class to obtain user input Data typesWhat are they? Know the basic types like: int, double, boolean, String, etc. Variables What is a variable? Declarations Initialization Assignment Constants Reserved words like: What is a reserved word? Examples:...

  • Using loops with the String and Character classes. You can also use the StringBuilder class to...

    Using loops with the String and Character classes. You can also use the StringBuilder class to concatenate all the error messages. Floating point literals can be expressed as digits with one decimal point or using scientific notation. 1 The only valid characters are digits (0 through 9) At most one decimal point. At most one occurrence of the letter 'E' At most two positive or negative signs. examples of valid expressions: 3.14159 -2.54 2.453E3 I 66.3E-5 Write a class definition...

  • From the Tony Gaddis text, the chapter on C-String and Class String: String Length: Write a...

    From the Tony Gaddis text, the chapter on C-String and Class String: String Length: Write a Function that passes in a C-String and using a pointer determine the number of chars in the string.                                           Data:   “This is a test string for string length” Prt String Backwards: Write a Function that passes in a C-String and prints the string backwards.      Data: “This is a test string for string backwards” replaceSubstring: Write a Function that accepts three C-Strings – str1,...

  • Create a program that performs the following operations: Prompt for and accept a string of up...

    Create a program that performs the following operations: Prompt for and accept a string of up to 80 characters from the user. • The memory buffer for this string is created by: buffer: .space 80 # create space for string input • The syscall to place input into the buffer looks like: li $v0, 8 # code for syscall read_string la $a0, buffer # tell syscall where the buffer is li $a1, 80 # tell syscall how big the buffer...

  • Write a program in java to read a string object consisting 300 characters or more using...

    Write a program in java to read a string object consisting 300 characters or more using index input Stream reader. The program should perform following operations. The String must have proper words and all kind of characters.(Use String class methods). a, Determine the length of the string count the number of letters in the strings , count the number of numeric object d. Calculate the number of special character e. Compute the ratio of the numeric to the total f....

  • Convert Code from Java to C++ Convert : import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class...

    Convert Code from Java to C++ Convert : import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Template { public static void main(String args[]) { Scanner sc1 = new Scanner(System.in); //Standard input data String[] line1 = sc1.nextLine().split(","); //getting input and spliting on basis of "," String[] line2 = sc1.nextLine().split(" "); //getting input and spiliting on basis of " "    Map<String, String> mapping = new HashMap<String, String>(); for(int i=0;i<line1.length;i++) { mapping.put(line1[i].split("=")[0], line1[i].split("=")[1]); //string in map where in [] as key and...

  • Class StringImproved public class StringImproved extends java.lang.Object This program replaces the string class with a mutable...

    Class StringImproved public class StringImproved extends java.lang.Object This program replaces the string class with a mutable string. This class represents a character array and provide functionalities need to do basic string processing. It contains an array of characters, representing a textual string. Overview In Java, Strings are a great device for storing arrays of characters. One limitation of Strings in Java, however (there is always at least one), is that they are immutable (ie. they cannot be changed once created)....

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