简体   繁体   中英

How can I move the punctuation from the end of a string to the beginning?

I am attempting to write a program that reverses a string's order, even the punctuation. But when my backwards string prints. The punctuation mark at the end of the last word stays at the end of the word instead of being treated as an individual character.

How can I split the end punctuation mark from the last word so I can move it around?

For example: When I type in : Hello my name is jason!

I want: !jason is name my Hello

instead I get: jason! is name my Hello

import java.util.*;

class Ideone
{
        public static void main(String[] args) {

        Scanner userInput = new Scanner(System.in);

        System.out.print("Enter a sentence: ");

        String input = userInput.nextLine();

        String[] sentence= input.split(" ");

        String backwards = "";

        for (int i = sentence.length - 1; i >= 0; i--) {
            backwards += sentence[i] + " ";
        }

        System.out.print(input + "\n");
        System.out.print(backwards);
        }
}

Manually rearranging Strings tends to become complicated in no time. It's usually better (if possible) to code what you want to do, not how you want to do it.

String input = "Hello my name is jason! Nice to meet you. What's your name?";

// this is *what* you want to do, part 1:
// split the input at each ' ', '.', '?' and '!', keep delimiter tokens
StringTokenizer st = new StringTokenizer(input, " .?!", true);
StringBuilder sb = new StringBuilder();
while(st.hasMoreTokens()) {
    String token = st.nextToken();
    // *what* you want to do, part 2:
    // add each token to the start of the string
    sb.insert(0, token);
}

String backwards = sb.toString();

System.out.print(input + "\n");
System.out.print(backwards);

Output:

Hello my name is jason! Nice to meet you. What's your name?
?name your What's .you meet to Nice !jason is name my Hello

This will be a lot easier to understand for the next person working on that piece of code, or your future self.

This assumes that you want to move every punctuation char. If you only want the one at the end of the input string, you'd have to cut it off the input, do the reordering, and finally place it at the start of the string:

String punctuation = "";
String input = "Hello my name is jason! Nice to meet you. What's your name?";
System.out.print(input + "\n");
if(input.substring(input.length() -1).matches("[.!?]")) {
    punctuation = input.substring(input.length() -1);
    input = input.substring(0, input.length() -1);
}

StringTokenizer st = new StringTokenizer(input, " ", true);
StringBuilder sb = new StringBuilder();
while(st.hasMoreTokens()) {
    sb.insert(0, st.nextToken());
}
sb.insert(0, punctuation);
System.out.print(sb);

Output:

Hello my name is jason! Nice to meet you. What's your name?
?name your What's you. meet to Nice jason! is name my Hello

You need to follow the below steps:

(1) Check for the ! character in the input

(2) If input contains ! then prefix it to the empty output string variable

(3) If input does not contain ! then create empty output string variable

(4) Split the input string and iterate in reverse order (you are already doing this)

You can refer the below code:

public static void main(String[] args) {
     Scanner userInput = new Scanner(System.in);
     System.out.print("Enter a sentence: ");
     String originalInput = userInput.nextLine();
     String backwards = "";
     String input = originalInput;

      //Define your punctuation chars into an array
       char[] punctuationChars = {'!', '?' , '.'};
        String backwards = "";

          //Remove ! from the input
         for(int i=0;i<punctuationChars.length;i++) {
          if(input.charAt(input.length()-1) == punctuationChars[i]) {
              input = input.substring(0, input.length()-1);
              backwards = punctuationChars[i]+"";
              break;
          }
        }

        String[] sentence= input.split(" ");


        for (int i = sentence.length - 1; i >= 0; i--) {
            backwards += sentence[i] + " ";
        }

        System.out.print(originalInput + "\n");

        System.out.print(input + "\n");
        System.out.print(backwards);
    }

Like the other answers, need to separate out the punctuation first, and then reorder the words and finally place the punctuation at the beginning.

You could take advantage of String.join() and Collections.reverse(), String.endsWith() for a simpler answer...

String input = "Hello my name is jason!";
String punctuation = "";
if (input.endsWith("?") || input.endsWith("!")) {
    punctuation = input.substring(input.length() - 1, input.length());
    input = input.substring(0, input.length() - 1);
}
List<String> words = Arrays.asList(input.split(" "));
Collections.reverse(words);
String reordered = punctuation + String.join(" ", words);
System.out.println(reordered);

The below code should work for you

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceSample {
    public static void main(String[] args) {
        String originalString = "TestStr?";
        String updatedString = "";
        String regex = "end\\p{Punct}+|\\p{Punct}+$";
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(originalString);
    while (matcher.find()) {
            int start = matcher.start();
            updatedString = matcher.group() + originalString.substring(0, start);<br>
        }
        System.out.println("Original -->" + originalString + "\nReplaced -->" +      updatedString);
    }
}

Don't split by spaces; split by word boundaries. Then you don't need to care about punctuation or even putting spaces back, because you just reverse them too!

And it's only 1 line:

Arrays.stream(input.split("\\b"))
    .reduce((a, b) -> b + a)
    .ifPresent(System.out::println);

See live demo .

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