java 将句子中的每两个单词颠倒

7dl7o3gd  于 2023-04-28  发布在  Java
关注(0)|答案(7)|浏览(216)

我试着把每个句子的第二个词都倒过来
如果给定的字符串是:

My name is xyz

所需输出应为:

My eman is zyx

我的当前输出是:

Ym eman s1 zyx

我无法实现我想要的输出。不知道我做错了什么
这是我的代码

char[] sentence = "  Hi my name is person!".toCharArray();
    System.out.println(ReverseSentence(sentence));

}
private static char[] ReverseSentence(char[] sentence)
{
    //Given: "Hi my name is person!"
    //produce: "iH ym eman si !nosrep"

    if(sentence == null) return null;
    if(sentence.length == 1) return sentence;

    int startPosition=0;
    int counter = 0;
    int sentenceLength = sentence.length-1;

    //Solution handles any amount of spaces before, between words etc...

    while(counter <= sentenceLength)
    {
        if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word
        {
            //swap from startPos to counter - 1
            //set start position to -1 and increment counter
            int begin = startPosition;

            int end;
            if(sentenceLength == counter)
            {
                end = counter;
            }
            else
                end = counter -1;
            char tmp;

            //Reverse characters
            while(end >= begin){

                tmp = sentence[begin];
                sentence[begin] = sentence[end];
                sentence[end] = tmp;

                end--; begin++;

            }

            startPosition = -1; //flag used to indicate we have no encountered a character of a string

        }

        else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position
        {
            startPosition = counter;
        }

        counter++;
    }

    return sentence;
}
wixjitnu

wixjitnu1#

如果你想反转替代单词,你可以尝试将整个String分割成由空格分隔的单词,并在每个第二个单词上应用StringBuilder reverse(),如:-

String s = "My name is xyz";
        String[] wordsArr = s.split(" "); // broke string into array delimited by " " whitespace
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i< wordsArr.length; i++){ // loop over array length
            if(i%2 == 0) // if 1st word, 3rd word, 5th word..and so on words 
                sb.append(wordsArr[i]); // add  the word as it is
            else sb.append(new StringBuilder(wordsArr[i]).reverse()); // else use StringBuilder revrese() to reverse it
            sb.append(" ");// add a whitespace in between words
        }
        System.out.println(sb.toString().trim()); //remove extra whitespace from the end and convert StringBuilder to String

输出:-My eman is zyx

vnzz0bqm

vnzz0bqm2#

你可以用各种简单的方法来解决你的问题!只要使用一个flag变量,它将指示 evenodd 位置,更准确地说,任何单词是否会被反转!
看看我在你的代码中做的以下修改,只是增加了三行:

private static boolean flag = true;// added a variable flag to check if we reverse the word or not.
private static char[] ReverseSentence(char[] sentence)
{
    //Given: "Hi my name is person!"
    //produce: "iH ym eman si !nosrep"

    if(sentence == null) return null;
    if(sentence.length == 1) return sentence;

    int startPosition=0;
    int counter = 0;
    int sentenceLength = sentence.length-1;

    //Solution handles any amount of spaces before, between words etc...

    while(counter <= sentenceLength)
    {
        if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word
        {
            flag = !flag; // first time (odd position) we are not going to reverse!
            //swap from startPos to counter - 1
            //set start position to -1 and increment counter
            int begin = startPosition;

            int end;
            if(sentenceLength == counter)
            {
                end = counter;
            }
            else
                end = counter -1;
            char tmp;

            //Reverse characters
            while(end >= begin & flag){ //lets see whether we are going to reverse or not

                tmp = sentence[begin];
                sentence[begin] = sentence[end];
                sentence[end] = tmp;

                end--; begin++;

            }

            startPosition = -1; //flag used to indicate we have no encountered a character of a string

        }

        else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position
        {
            startPosition = counter;
        }

        counter++;
    }

    return sentence;
}

输入
我叫xyz
输出:
我的男人是zyx

yxyvkwin

yxyvkwin3#

下面的代码执行这个“特殊反转”,它反转了句子中的任何其他单词:

public static void main(String[] args) {
    String sentence = "My name is xyz";
    System.out.println(specialReverse(sentence)); //  My eman is zyx
}

private static String specialReverse(String sentence) {
    String result = "";
    String[] words = sentence.split(" ");
    // we'll reverse only every second word according to even/odd index
    for (int i = 0; i < words.length; i++) {
        if (i % 2 == 1) {
            result += " " + reverse(words[i]);
        } else {
            result += " " + words[i];
        }
    }
    return result;
}

// easiest way to reverse a string in Java in a "one-liner"
private static String reverse(String word) {
    return new StringBuilder(word).reverse().toString();
}
deyfvvtc

deyfvvtc4#

为了完整起见,这里是Java-8解决方案:

public static String reverseSentence(String input) {
    String[] words = input.split(" ");
    return IntStream.range(0, words.length)
            .mapToObj( i -> i % 2 == 0 ? words[i] : 
                    new StringBuilder(words[i]).reverse().toString())
            .collect(Collectors.joining(" "));
}

reverseSentence("My name is xyz"); // -> My eman is zyx
57hvy0tb

57hvy0tb5#

package com.eg.str;

// Without using StringBuilder  
// INPUT: "Java is very cool prog lang"
// OUTPUT: Java si very looc prog gnal

public class StrRev {
    
    public void reverse(String str) {
        String[] tokens = str.split(" ");
        String result = "";
        String k = "";
        for(int i=0; i<tokens.length; i++) {
            if(i%2 == 0)
                System.out.print(" " + tokens[i] + " ");
            else
                result = tokens[i];
                
                for (int j = result.length()-1; j >= 0; j--)  {
                    k = "" + result.charAt(j);
                    System.out.print(k);
                }
                result = "";
        }   
    }
    
    

    public static void main(String[] args) {
        
        StrRev obj = new StrRev();
        obj.reverse("Java is very cool prog lang");
    }
}
xxe27gdn

xxe27gdn6#

//在java public class ReverseSecondWord中反转句子的第二个单词{

public static void main(String[] args) {
    
    String s="hello how are you?";
    String str[]=s.split(" ");
    String rev="";
    
    for(int i=0;i<str[1].length();i++)
    {
    char ch=str[1].charAt(i);
    rev=ch+rev;
    }       
    str[1]=rev;     
    for(int i=0;i<str.length;i++)
    {
        System.out.print(str[i]+" ");
    }
}

}

myss37ts

myss37ts7#

导入java。util.扫描仪;
public class Reverse_alternate_word { public static String reverseWord(String str){ // input:我的名字是rohit char ch;//输出:我的男人是tihor String rev="";

for(int i=0; i<str.length(); i++){
         ch = str.charAt(i);
         rev =ch + rev;
    }
    return  rev;
}
public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    String sentence=sc.nextLine();

    int count = 0;
    String arr[] = sentence.split(" ");
    for(int i=0; i< arr.length; i++)
    {
        if(i%2==1){
           String rev_word= reverseWord(arr[i]);
            System.out.print(rev_word+" ");
        }else{
            System.out.print(arr[i]+" ");
        }
    }
}

}

相关问题