簡體   English   中英

如何將標點符號從字符串的結尾移到開頭?

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

我試圖編寫一個程序來顛倒字符串的順序,甚至標點符號。 但是當我向后的字符串打印出來時。 最后一個單詞末尾的標點符號留在單詞末尾,而不是被視為單個字符。

如何將最后一個標點符號與最后一個單詞分開,以便可以移動它?

例如:當我輸入時:Hello,我的名字叫jason!

我想要:傑森是我的名字

相反,我得到:傑森! 我叫你好

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);
        }
}

手動重新排列字符串會立即變得復雜。 它通常是更好(如果可能)的代碼,你想做什么 ,你不是要怎么做。

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);

輸出:

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

對於下一個從事該代碼段工作的人或您自己的未來,這將更容易理解。

假設您要移動每個標點符號。 如果只想在輸入字符串的末尾添加一個,則必須將其切斷輸入,進行重新排序,最后將其放置在字符串的開頭:

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);

輸出:

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

您需要執行以下步驟:

(1)檢查! 輸入中的字符

(2)如果輸入包含! 然后將其前綴為空的輸出字符串變量

(3)如果輸入不包含! 然后創建空的輸出字符串變量

(4)分割輸入字符串並以相反的順序進行迭代(您已經在執行此操作)

您可以參考以下代碼:

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);
    }

像其他答案一樣,需要先將標點符號分開,然后對單詞重新排序,最后將標點符號放在開頭。

您可以利用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);

下面的代碼應該為您工作

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);
    }
}

不要被空格分開; 按單詞邊界分割。 然后,您無需擔心標點符號,甚至不必放空格,因為您也可以將它們反向!

而且只有1行:

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

觀看現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM