简体   繁体   中英

Rotating a Sentence by n words

I'm am trying to update a code that I have previously written to "rotate a String." Currently my program accepts a string from keyboard input and an integer n. ex. "abcdefg", 3. Then rotates the string by n characters before returning the rotated string ie "efgabcd". Now for the tricky part. I'm trying to update this to do essentially the same thing but with a sentence. So the inputs would be a something like "This is an example" and an integer 3. then the output would be "is an example this." I assume splitting the sentence into an array would be my best bet; however my unfamiliarity with strings doesn't allow my to know how to go about doing this.

import java.util.*;
public class Rotate
{
  public static String rotate(String s, int num)
{
    int length = s.length();
    String a = s.substring(0,(length-num));
    String b = s.substring((length-num),length);
    String c = b + a;
    return c;
}


public static void main(String[] args)
{
  Scanner input = new Scanner(System.in);
  System.out.print("Enter a string:");
  String s = input.nextLine();
  System.out.print("Enter the number of characters that you want to rotated to right:");
  int n =input.nextInt();
  String t = rotate(s, n);
  System.out.println("The rotated string is "+ t);
 }
}

Here's a sample solution:

int num = 3;
String str = "This is a test";
String[] strArr = str.split(" ");
int length = strArr.length;
String[] temp = Arrays.copyOfRange(strArr, length - num, length);
System.arraycopy(strArr, 0, strArr, num, length - num);
System.arraycopy(temp, 0, strArr, 0, temp.length);
str = String.join(" ", strArr);

str now contains "is a test This".

EDIT: Fixed to rotate to right.

I actually prefer @fergDEV's solution, but it can be cleaned up a bit if you're using Java 8:

int num = 3;
String str = "This is a test";
List<String> parts = Arrays.asList(str.split(" "));
Collections.rotate(parts, 3);
String.join(" ", parts);

The Collections utils are your friend :P.

public class Main {
    public static String rotateSetence(final String input, final int rotation) {
        final List<String> results = Arrays.asList(input.split(" "));
        Collections.rotate(results, rotation);

        final StringBuilder outputBuilder = new StringBuilder();

        for (int i = 0; i < results.size(); i++) {
            outputBuilder.append(results.get(i));
            if (i != results.size() - 1)
                outputBuilder.append(" ");
        }
        return outputBuilder.toString();
    }

    public static void main(String[] args) {
        final String inputString = "This is an example";
        final int sentenceRotation = 3;
        final String expectedResult = "is an example This";

        final String result = rotateSetence(inputString, sentenceRotation);
        System.out.println("result " + result);
        if (result.equals(expectedResult)) {
            System.out.println("Passed");
        } else {
            System.out.println("Failed");
        }
    }
}

EDIT

The builder code can be replaced with string.join ... thanks to @shmosel.

        final StringBuilder outputBuilder = new StringBuilder();

        for (int i = 0; i < results.size(); i++) {
            outputBuilder.append(results.get(i));
            if (i != results.size() - 1)
                outputBuilder.append(" ");
        }
        return outputBuilder.toString();

can be replaced with

    return String.join(" ", results);

You can also make use of two for loops, such that in the first for loop you loop from num (provided by user) position to the end of the string. And in the second loop you loop from start of string until the position of num.

For above logic to work, you obviously need to split your string using space into array of strings. See below:

public static String rotate(String s, int num)
    {
        //split the sentence by space
        String[] chunks = s.split(" ");
        //use StringBuilder to build rotated string 
        StringBuilder builder = new StringBuilder();

        //loop from position specified by user to end of array
        for(int i = num; i < chunks.length; i++) {
            builder.append(chunks[i] + " "); 
        }

        //loop from start of array to position specified by user
        for(int i = 0; i < num; i++) {
            builder.append(chunks[i] + " "); 
        }
        return builder.toString();
    }

The input and output is shown below:

Enter a string:My name is Raf and I am super super fun guy trust me 
Enter the number of characters that you want to rotated to right:2
The rotated string is :  is Raf and I am super super fun guy trust me My name 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM