【问题标题】:How can I move the punctuation from the end of a string to the beginning?如何将标点符号从字符串的末尾移到开头?
【发布时间】:2016-11-19 20:57:59
【问题描述】:

我正在尝试编写一个程序来反转字符串的顺序,甚至是标点符号。但是当我的向后字符串打印时。最后一个单词末尾的标点符号保留在单词的末尾,而不是被视为单个字符。

如何将结尾标点符号与最后一个单词分开,以便可以移动它?

例如: 当我输入:你好,我的名字是 jason!

我想要:!jason 是我的名字 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);
        }
}

【问题讨论】:

  • 你的落后定义怎么可能? ! 不是一个单独的词来获得你想要的东西。可以做到,但是您的反向字符串顺序的想法是错误的。
  • 在每个单词上,检查endsWith 是否不是字母。如果是这样,请将其移至单词的开头。瞧。

标签: java arrays string loops split


【解决方案1】:

手动重新排列字符串很快就会变得复杂。通常最好(如果可能的话)编写你想要做的什么,而不是你想怎么做

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

【讨论】:

  • 这样我可以更深入地了解,你能详细说明一下这条线吗? : 字符串令牌 = st.nextToken();
  • StringTokenizer 将在与分隔符字符串中的一个字符匹配的每个字符处拆分输入(new StringTokenizer(input, " .?!", true); 中的第二个参数,所以 ' ' 又名空格,.,?! 在这个例子中)。每次调用st.nextToken() 都将返回分割字符串的下一部分——该类调用这些标记。
【解决方案2】:

和其他答案一样,需要先把标点分开,然后重新排列单词,最后把标点放在开头。

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

【讨论】:

    【解决方案3】:

    下面的代码应该适合你

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

    【讨论】:

      【解决方案4】:

      您需要按照以下步骤操作:

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

      【讨论】:

      • 标题中特别提到“将标点从字符串的末尾移到开头”。他只是提供了一个使用! 的示例。您还应该考虑字符串中间的标点符号。请编辑您的答案和代码以满足所有符号(以更通用的方式)
      • @SkrewEverything 是的,你是对的,通过将标点字符定义为数组并检查字符并添加来更新我的答案。
      • 我想你忘了编辑一些 cmets 和最后一个 if 块。并且请在开头的解释中更改!,并将其替换为? . !
      • @SkrewEverything 现在看起来还好吗?
      【解决方案5】:

      不要用空格分隔;按单词边界分割。那么你就不需要关心标点符号甚至把空格放回去了,因为你也只是把它们颠倒了!

      而且只有 1 行:

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

      live demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多