0

This is my first question in stack overflow so forgive me if I am going against the rules.

I want to take user input as string and reverse every nth word of the string. The n value is also entered by the user. If the user inputs invalid value the program should respond the user accordingly. Until now, I am able to take a string input and reverse the whole string. I need help to take nth value as an input and reverse the string with the n value. And the program should run without using "String.reverse" or any other string function. Hopefully, I elaborated every aspect of the problem. Thanks :)

Sample I/O should look like:

User Input = "Hello World! Programming is fun"
User Inputs n value = "2"
Expected Output = "Hello !dlroW Programming si fun"
User inputs n-value "2", which means every second word should be reversed.

Following is the program that I wrote till now:

 import java.util.*;

    public class StringReverse {

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Scanner in = new Scanner(System.in);

            String original, reverse="";

            System.out.print("Please enter a sentence to reverse: ");

            original= in.nextLine();

            for (int i=original.length()-1; i>=0; i--) {
                reverse += original.charAt(i);
            }
            System.out.println(reverse);    
        }
    }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    You forgot to ask an actual question. – Mark Rotteveel Mar 20 '18 at 14:37
  • 1
    @MarkRotteveel Hi Mark, Thanks for the response. I want to write a program to take a string 's' from the user. The string is expected to be a series of words. Following the string, the user will also enter an integer value 'n'. The program should pass through the String and reverse every 'nth' word. – Dev_elop_er_ Mar 20 '18 at 14:39
  • 1
    Can you post a sample output? – Juan Carlos Mendoza Mar 20 '18 at 14:40
  • So your question is "you don't know how to do it"? Hint: use `next` method of `Scanner` to read each word, and modulo `%` to check if the index is a multiple of another number. – user202729 Mar 20 '18 at 14:41
  • @JuanCarlosMendoza Hi Juan. Unfortunately I dont have any sample output as this problem is given in assignment and I couldn't find any possible solution to solve this. – Dev_elop_er_ Mar 20 '18 at 14:45
  • @HumxaFaroooq Assume you have fully understood the problem, you can as well give a sample input/output by working out a small test case by hand. – user202729 Mar 20 '18 at 14:46
  • You could try to `split()` the `String` into tokens (there is a method in `String`) and then only reverse the words you want. – Uwe Plonus Mar 20 '18 at 14:46
  • @user202729 Sorry for the inconvenience, Sample I/O: User Input: “Hello World, My name is Joe Bloggs”, nth value = 2 Output: “Hello dlroW, My eman is eoJ sggolB” – Dev_elop_er_ Mar 20 '18 at 14:49
  • @UwePlonus Actually I have to write the program without using string tokens :( – Dev_elop_er_ Mar 20 '18 at 14:49
  • You can [edit] the question to add more information. [Avoid too much salutation](https://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). – user202729 Mar 20 '18 at 14:49
  • `split()` is a method from `String`... – Uwe Plonus Mar 20 '18 at 14:50
  • @UwePlonus Probably "for learning purposes". Can either be good or bad. Also see [this](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question#comment146126_284236). – user202729 Mar 20 '18 at 14:50
  • @UwePlonus Hahah That was informative :D I would love to ask my teacher that question. So is it against the rules of stackoverflow to ask these questions ? – Dev_elop_er_ Mar 20 '18 at 14:59
  • 1
    You still haven't asked an actual question. You have described the background/context (or your 'assignment'), but you still haven't asked a question (a sentence that ends in a '?'), or at minimum explicitly defined what you're currently stuck on (just showing code and expecting us to fill in the blanks is a bit much). – Mark Rotteveel Mar 20 '18 at 15:30

3 Answers3

1

Iterate your String and append (+) every character in a separated String until you reach a whitespace (' '). If a whitespace occures you have a word which you can store and count.

Reverse the n-th word by iterating the word from behind (i-- like in your actual code) and add every character to a String so you have a reversed word by simply adding the characters.

I don't know whether concatenating (+) of String is allowed in your situation?

Sounds like homework so i just give you some inspiration.

Happy coding! :)

M_I
  • 132
  • 5
  • Thanks mate. I will try this solution and will let you know. And thanks for understanding my homework situation Happy Coding – Dev_elop_er_ Mar 20 '18 at 15:20
1

You can try with following code.

import java.util.Scanner;

public class March21th {

    private static Scanner sc;

    public static void main(String[] args) {

        sc = new Scanner(System.in);
        System.out.print("Please enter a sentence to reverse: ");
        String str = sc.nextLine();
        System.out.print("Please enter nth value: ");
        int n = sc.nextInt();

        String[] strArr = str.split(" ");
        int len = strArr.length;

        String str2 = strArr[n-1];
        //System.out.println("str2: "+str2);
        String strrev2 = strArr[len-n];
        //System.out.println("strrev2: "+strrev2);

        char temp;
        char[] str2CharArr = str2.toCharArray();
        char[] strrev2CharArr = strrev2.toCharArray();
        int str2CharArrLen = str2CharArr.length;
        int strrev2CharArrLen = strrev2CharArr.length;
        //System.out.println("str2CharArrLen: "+str2CharArrLen);
        //System.out.println("strrev2CharArrLen: "+strrev2CharArrLen);

        for(int i=0,j=str2CharArrLen-1;i<str2CharArrLen/2;i++,j--) {
            temp = str2CharArr[i];
            str2CharArr[i] = str2CharArr[j];
            str2CharArr[j] =  temp;
        }
        String str2CharArrRev = String.valueOf(str2CharArr);
        //System.out.println("str2CharArr after reverse: "+str2CharArrRev);

        for(int i=0,j=strrev2CharArrLen-1;i<strrev2CharArrLen/2;i++,j--) {
            temp = strrev2CharArr[i];
            strrev2CharArr[i] = strrev2CharArr[j];
            strrev2CharArr[j] =  temp;
        }
        String strrev2CharArrRev = String.valueOf(strrev2CharArr);
        //System.out.println("strrev2CharArr after reverse: "+strrev2CharArrRev);

        strArr[n-1] = str2CharArrRev;
        strArr[len-n] = strrev2CharArrRev;
        //System.out.println("strArr[n-1]: "+strArr[n-1]);
        //System.out.println("strArr[len-n]: "+strArr[len-n]);

        String revStr = "";
        for(int i=0; i<len;i++) {
            revStr += strArr[i]+" ";
        }
        System.out.println(revStr);
    }
 }

input:

String str = "Hello World! Programming is fun";

output:

Hello !dlroW Programming si fun 

If you don't want to use split() function then take help form this page

Atequer Rahman
  • 1,171
  • 10
  • 25
  • I've tested your implementation but it is working not working as expected: **Input** `Hey Java! Let's reverse this sentence here for testing!`; **n-th value:** 2; **Output:** `Hey !avaJ Let's reverse this sentence here rof testing!` – M_I Mar 22 '18 at 15:46
  • It is working as expected.Can you write the exact output you are getting? – Atequer Rahman Mar 22 '18 at 16:01
  • If you get output like this_ `revStr: Hey !avaJ Let's reverse this sentence here rof testing!` don't worry. I printed `revStr:` for testing purpose. I have edited the code and removed it. Now you should get expected output. – Atequer Rahman Mar 22 '18 at 16:11
0

I just had some time to implement another version of reversing a sentence with n-th value. Just a good practice. ;)

public static void main(String[] args) {

    sc = new Scanner(System.in);
    System.out.print("Please enter a sentence to reverse: ");
    String sentence = sc.nextLine();

    System.out.print("Please enter nth value: ");
    int nthValue = sc.nextInt();

    System.out.println(reverseSentence(sentence, nthValue));
}

private static String reverseSentence(String sentence, int nthValue) {

    String reversedSentence = "";
    String word = "";
    int wordCount = 1;

    char[] sentenceChar = sentence.toCharArray();

    for (int i=0; i < sentenceChar.length; i++) {
        char letter = sentenceChar[i];
        // letter is whitespace or end of sentence?
        if ((letter == ' ') || i == sentenceChar.length - 1) {
            // match n-th value?
            if (wordCount % nthValue == 0) {
                reversedSentence += reverseWord(word) + ' ';
            } else {
                reversedSentence += word + ' ';
            }
            wordCount++;
            word = "";
        } else {
            word += letter;
        }
    }

    return reversedSentence;
}

private static String reverseWord(String word) {
    String reversedWord = "";
    char[] wordChar = word.toCharArray();
    for (int i=wordChar.length - 1; i >= 0; i--) {
        reversedWord += wordChar[i];
    }
    return reversedWord;
}
M_I
  • 132
  • 5