代码之家  ›  专栏  ›  技术社区  ›  MARTIN

交换第一个和最后一个单词,反转所有中间的字符

  •  0
  • MARTIN  · 技术社区  · 10 月前

    说明

    古鲁给他的学生布置了一项任务。他给了一个句子,学生们必须交换第一个和最后一个单词,并颠倒所有中间的字符。帮助学生使用java程序解决此任务

    要求:

    •    The words present in the sentence must be more than 2, else print "Invalid Length"
      
    •    The word should contain only alphabets and space, else print "<sentence> is an invalid sentence"
      

    注:

    •    In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given by the user, and the rest of the text represents the output.
      
    •    Ensure to follow the object-oriented specifications provided in the question description.
      
    •    Ensure to provide the names for classes, attributes, and methods as specified in the question description.
      
    •    Adhere to the code template, if provided
      

    请不要使用System.exit(0)终止程序。

    示例输入/输出1:

    输入句子

    你戴口罩了吗

    面具ruoy raew uoy Do

    示例输入/输出2:

    输入句子

    读卡器

    长度无效

    示例输入/输出3:

    输入句子

    推荐@好友

    Reflect@friend是一个无效的句子

    代码:-

    import java.util.Scanner;
    
    class SentenceProcessor {
        
        // Method to check if the sentence is valid
        public boolean isValidSentence(String sentence) {
            return sentence.matches("[a-zA-Z ]+"); // Only alphabets and spaces allowed
        }
    
        // Method to process the sentence
        public String processSentence(String sentence) {
            if (!isValidSentence(sentence)) {
                return sentence + " is an invalid sentence";
            }
    
            String[] words = sentence.trim().split("\\s+"); // Split by whitespace
    
            if (words.length <= 2) {
                return "Invalid Length";
            }
    
            // Swap first and last words
            String firstWord = words[0];
            String lastWord = words[words.length - 1];
            words[0] = lastWord;
            words[words.length - 1] = firstWord;
    
            // Reverse middle words
            for (int i = 1; i < words.length - 1; i++) {
                words[i] = new StringBuilder(words[i]).reverse().toString();
            }
    
            return String.join(" ", words); // Join words with a space
        }
    }
    
    public class UserInterface {
        
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            
            System.out.println("Enter the sentence");
            String input = sc.nextLine();
            
            SentenceProcessor processor = new SentenceProcessor();
            String result = processor.processSentence(input);
            
            System.out.println(result);
            
            sc.close(); // Close the scanner to avoid resource leaks
        }
    }
    

    输出:-

    Enter the sentence
    Do you wear your mask
    mask uoy raew ruoy Do
    

    预期产量:-

    Enter the sentence
    Do you wear your mask
    mask ruoy raew uoy Do
    

    我尝试解决这个问题,但未能获得所需的输出,还尝试使用各种开源,这些开源也无法给我正确的代码,它们反复给我相同的输出(如chatgpt、copilot)

    4 回复  |  直到 10 月前
        1
  •  2
  •   WJS    10 月前

    问题是你颠倒了每个单词的字符。但你说你应该颠倒第一个和最后一个单词之间的所有字符。

    假设中间的单词是 one two three .
    你正在做 eno owt eerht .
    你想要的是 eerht owt eno .

    请执行以下操作:

    • 获取第一个空格和最后一个空格之间的子字符串。
    • 然后反转中间的子字符串
    • 并按照正确的顺序附加单词和子字符串
    // Reverse middle characters (those between first and last word)
    int start = sentence.indexOf(" ") + 1;
    String middle = new StringBuilder(
            sentence.substring(start, sentence.lastIndexOf(" "))).reverse()
            .toString();
    
    return String.join(" ", lastWord, middle, firstWord); // Join sections with a space
    
        2
  •  2
  •   wannaBeDev    10 月前

    为了得到想要的结果,你需要交换数组的元素:第二个单词和倒数第二个,第三个单词和最后第三个。。。等等。也许它更容易使用 String.substring 方法用于整个任务,而不是将输入拆分到数组中:

    public String processSentence(String sentence) {
        if (!isValidSentence(sentence)) {
            return sentence + " is an invalid sentence";
        }
    
        int firstSpaceIndex = sentence.indexOf(' ');
        int lastSpaceIndex  = sentence.lastIndexOf(' ');
    
        String firstWord  = sentence.substring(0, firstSpaceIndex);
        String lastWord   = sentence.substring(lastSpaceIndex + 1);
        String middlePart = sentence.substring(firstSpaceIndex, lastSpaceIndex + 1);
    
        return lastWord + new StringBuilder(middlePart).reverse() + firstWord;
    }
    

    编辑

    检查输入字符串是否至少有三个子字符串由空格分隔,即单词计数>2修改您进行验证的第二种方法。这样做可以将处理和验证的任务分开。

    public boolean isValidSentence(String sentence) {
        String regex = "^[a-zA-Z]+(\\s[a-zA-Z]+){2,}$";
        return sentence.trim().matches(regex);
    }
    

    正则表达式说明: ^[a-zA-Z]+(\\s[a-zA-Z]+){2,}$

    • ^ 确保字符串以第一个子字符串开头。

    • [a-zA-Z]+ 匹配字母序列(子字符串)。

    • (\\s[a-zA-Z]+) 匹配一个空格后跟另一个子字符串。

    • {2,} 确保在第一个子字符串之后至少有2个子字符串。

    • $ 确保整个字符串都符合图案。

        3
  •  1
  •   SedJ601    10 月前

    您的要求与预期的输出不匹配!

    // Method to process the sentence
    static public String processSentence(String sentence) {
        if (!isValidSentence(sentence)) {
            return sentence + " is an invalid sentence";
        }
    
        String[] words = sentence.trim().split("\\s+"); // Split by whitespace
    
        if (words.length <= 2) {
            return "Invalid Length";
        }
    
        //Swap all words
        String[] reverseWords = new String[words.length];
        for(int i = words.length - 1; i >= 0; i--)
        {
            reverseWords[(reverseWords.length - 1) - i] = words[i];
        }
    
        // Reverse middle words
        for (int i = 1; i < words.length - 1; i++) {
            reverseWords[i] = new StringBuilder(reverseWords[i]).reverse().toString();
        }
    
        return String.join(" ", reverseWords); // Join words with a space
    }
    

    输出:

    Do you wear your mask
    mask ruoy raew uoy Do
    
        4
  •  1
  •   Marce Puente    10 月前

    错误在这里:

    for (int i = 1; i < words.length - 1; i++) {
        words[i] = new StringBuilder( words[i] ).reverse().toString();
    }
    

    问题是,你颠倒了中心单词的字母顺序,但没有颠倒它们的顺序,我们可以这样做:

    String out = lastWord + " ";
    for( int i = words.length - 2; i >= 1; i -- ) {
       out += new StringBuilder( words[ i ] ).reverse().toString() + " ";
    }
    return out + firstWord;