翻译句子的每个第二个单词

时间:2015-07-23 17:42:56

标签: java string

我试图扭转每一句话的每个第二个单词,如

如果给定的字符串是:

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

5 个答案:

答案 0 :(得分:2)

如果您想要反转替代词,您可以尝试将整个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

答案 1 :(得分:0)

以下代码执行此“特殊反向”,它会反转句子中的任何其他单词:

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

答案 2 :(得分:0)

您可以轻松解决您的问题!只需使用一个flag变量来指示偶数奇数位置,更确切地说是否会反转任何单词!

看看我在你的代码中做的以下修改,只添加了三行:

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

输出:

  

我的eman是zyx

答案 3 :(得分:0)

为了完整性,这里是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

答案 4 :(得分:0)

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