简体   繁体   English

如何将标点符号从字符串的结尾移到开头?

[英]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! 例如:当我输入时:Hello,我的名字叫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 ! (1)检查! character in the input 输入中的字符

(2) If input contains ! (2)如果输入包含! then prefix it to the empty output string variable 然后将其前缀为空的输出字符串变量

(3) If input does not contain ! (3)如果输入不包含! then create empty output string variable 然后创建空的输出字符串变量

(4) Split the input string and iterate in reverse order (you are already doing this) (4)分割输入字符串并以相反的顺序进行迭代(您已经在执行此操作)

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.join()和Collections.reverse(),String.endsWith()获得更简单的答案...

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: 而且只有1行:

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

See live demo . 观看现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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