逐字反转字符串,除了每个单词的最后一个字母

问题描述 投票:0回答:7

我想逐字反转字符串,除了每个单词的最后一个字母。

例如:

"Hello how are you"
->
lleHo ohw rae oyu

但我得到的输出为:

olleH woh era uoy

我无法修复每个单词的最后一个字母。

这是我的上述输出的 Java 代码:

public class Main

    {
    public static void main(String[] args) {
     String s = "Hello how are you  ";
      char [] ch = s.toCharArray();
      System.out.println(ch.length);
      int pos=0;
        for(int i=0;i<ch.length;i++)
        {
        
            if(ch[i]==' ')
            {
                   
                for(int j=i;j>=pos;j--)
                {
                    System.out.print(ch[j]);
                }
                pos=i+1;
                }
            }
    
    }
} 
java arrays string character
7个回答
1
投票

下面是解决问题的方法:

public class Main { 
    
    public static void main(String[] args) { 
        //call the reverseSentence Method
        reverseSentence("Hello how are you");
    } 
    
    public static void reverseSentence(String sentence) {
        

        //Replacing multiple space with a single space
        sentence = sentence.replaceAll("[ ]{2,}", " ");

        //Split the array and store in an array
        String [] arr = sentence.split(" ");
        
        StringBuilder finalString = new StringBuilder();
        
        //Iterate through the array using forEach loop
        for(String str : arr) {
            
            //Creating substring of the word, leaving the last letter
            String s = str.substring(0, str.length() - 1);
            
            //Creating StringBuilder object and reversing the String
            StringBuilder sb = new StringBuilder(s);
            //Reversing the string and adding the last letter of the work again.
            s = sb.reverse().toString() + str.charAt(str.length() - 1);
            
            //Merging it with the final result
            finalString.append(s).append(" ");
        }
        
        //Printing the final result
        System.out.println(finalString.toString().trim());
    }
} 

我所做的是,首先将所有单词拆分为空格并将其存储在数组中。现在迭代数组并从每个单词中获取子字符串,留下每个单词的最后一个字母。然后我使用 StringBuilder 来反转字符串。完成后,我将单词的最后一个字母添加到反转的字符串中,并将其与创建的 FinalString 合并。


1
投票

我会使用正则表达式

replaceAll
和 lambda 来处理反转。
\S+
匹配任何非空格字符序列。这样做的优点是可以优雅地处理任意空白。如果您想避免反转标点符号,可以使用
\w+
,尽管像
"isn't"
等匹配单词表明问题已转移到自然语言处理中。不过,我认为您的规范并没有那么复杂。

import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        String res = Pattern
            .compile("\\S+")
            .matcher("Hello how are you")
            .replaceAll(m -> {
                String s = m.group();
                return new StringBuilder(s.substring(0, s.length() - 1))
                    .reverse().toString() + s.charAt(s.length() - 1);
             });
        System.out.println(res); // => lleHo ohw rae oyu
    }
}

0
投票

您如何看待这个解决方案?

public class Main
{
    public static void main(String[] args) {
        String s = "Hello how are you  ";
        char [] ch = s.toCharArray();
        System.out.println(ch.length);
        int pos=0;
        for(int i=0;i<ch.length;i++)
        {
        
            if(ch[i]==' ')
            {
                System.out.print(ch[i]);
                for(int j=i-2;j>=pos;j--)
                {
                    System.out.print(ch[j]);
                }
                System.out.print(ch[i-1]);
                pos=i+1;
            }
        }
    
    }
} 

0
投票
public class Main {
    public static void main(String[] args) {
        String s = "Hello how are you  ";
        final List<String> list = Arrays.asList(s.split(" "));
        StringBuilder builder = new StringBuilder();
        list.forEach(item ->{
            StringBuilder itemBuilder = new StringBuilder(item);
            final String rStr = itemBuilder.reverse().toString();
            builder.append(rStr.substring(1,rStr.length())).append(rStr.substring(0,1)).append(" ");
        });
        System.out.println(builder.toString());
    }
}

0
投票

FP风格:

String str = "Hello how are you";

String res = Arrays.stream(str.split(" "))
  .map(s ->
    new StringBuilder(s.substring(0, s.length() - 1)).reverse().toString() + s.substring(s.length() - 1)
  )
  .reduce((s, s1) -> s + " " + s1)
  .orElse("");

System.out.println(res); // lleHo ohw rae oyu

0
投票

更简单的解决方案是对每个单词(在 string.split 之后)使用 Java Stack 数据结构,然后添加每个字母(token.length-1 除外)。

public static void main(String[] args) {
    String string = "Hello how are you  ";
    final String[] tokens = string.split(" ");
    for (String token : tokens) {
        final Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < token.length()-1; i++) {
            stack.push(token.charAt(i));
        }
        while (!stack.empty()) {
            System.out.print(stack.pop());
        }
        System.out.print(token.charAt(token.length()-1) + " ");
    }
}

0
投票

我觉得这个也不错。

String[] s = "Hello how are you".split(" ");
    String revSentence = "";
    for (int i=0; i<s.length;i++){
        String c = s[i];
        String revWord = "";
        {
            for (int j=c.length()-2;j>=0; j--)
            {
                revWord = revWord+c.charAt(j);
            }
            revWord =revWord+c.charAt(c.length()-1);
            revSentence =revSentence+revWord+" ";

        }
    }
    System.out.println(revSentence);//lleHo ohw rae oyu
© www.soinside.com 2019 - 2024. All rights reserved.