如何在字符串中翻转两个单词,Java

时间:2012-01-10 23:18:02

标签: java string split swap flip

所以说我有一个名为x的字符串=“Hello world”。我想以某种方式使它成为翻转这两个词,而不是显示“世界你好”。我对循环或数组不是很好,显然我是初学者。我可以通过拆分我的字符串来实现这一点吗?如果是这样,怎么样?如果没有,我怎么能这样做?感谢帮助,谢谢!

7 个答案:

答案 0 :(得分:6)

1)将字符串拆分为空格中的String数组。

String myArray[] = x.split(" ");

2)从数组中以相反的顺序创建包含单词的新字符串。

String newString = myArray[1] + " " + myArray[0];

使用StringBuilder代替连接的加分点。

答案 1 :(得分:1)

String abc = "Hello world";
String cba = abc.replace( "Hello world", "world Hello" );

abc = "This is a longer string. Hello world. My String";
cba = abc.replace( "Hello world", "world Hello" );

如果你愿意,你也可以爆炸你的字符串:

String[] pieces = abc.split(" ");
for( int i=0; i<pieces.length-1; ++i )
    if( pieces[i]=="Hello" && pieces[i+1]=="world" ) swap(pieces[i], pieces[i+1]);

还有很多其他方法可以做到。小心大写。您可以在if语句中使用.toUpperCase(),然后将匹配条件设置为大写,但将结果保留为原始大小写等。

答案 2 :(得分:1)

以下是解决方案:

import java.util.*;

public class ReverseWords {
public String reverseWords(String phrase) {
List<string> wordList = Arrays.asList(phrase.split("[ ]"));
Collections.reverse(wordList);

StringBuilder sbReverseString = new StringBuilder();
for(String word: wordList) {
sbReverseString.append(word + " ");
}

return sbReverseString.substring(0, sbReverseString.length() - 1);
}
}

以上解决方案由我编码,适用于Google Code Jam,并在此处发布博客:Reverse Words - GCJ 2010

答案 3 :(得分:1)

只需使用此方法,调用它并传递要拆分的字符串即可

static String reverseWords(String str) {

    // Specifying the pattern to be searched
    Pattern pattern = Pattern.compile("\\s");

    // splitting String str with a pattern
    // (i.e )splitting the string whenever their
    //  is whitespace and store in temp array.
    String[] temp = pattern.split(str);
    String result = "";

    // Iterate over the temp array and store
    // the string in reverse order.
    for (int i = 0; i < temp.length; i++) {
        if (i == temp.length - 1) {
            result = temp[i] + result;
        } else {
            result = " " + temp[i] + result;
        }
    }
    return result;
}

答案 4 :(得分:0)

根据您的具体要求,您可能希望拆分其他形式的空白(标签,多个空格等):

static Pattern p = Pattern.compile("(\\S+)(\\s+)(\\S+)");
public String flipWords(String in)
{
    Matcher m = p.matcher(in);
    if (m.matches()) {
        // reverse the groups we found
        return m.group(3) + m.group(2) + m.group(1);
    } else {
        return in;
    }
}

如果您想要更复杂,请参阅模式http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

的文档

答案 5 :(得分:0)

尝试以下内容:

String input = "how is this";
List<String> words = Arrays.asList(input.split(" "));
Collections.reverse(words);
String result = "";
for(String word : words) {
    if(!result.isEmpty()) {
        result += " ";
    }
    result += word;
}
System.out.println(result);

<强>输出:

this is how

答案 6 :(得分:0)

太多了?

private static final Pattern WORD = Pattern.compile("^(\\p{L}+)");
private static final Pattern NUMBER = Pattern.compile("^(\\p{N}+)");
private static final Pattern SPACE = Pattern.compile("^(\\p{Z}+)");

public static String reverseWords(final String text) {
    final StringBuilder sb = new StringBuilder(text.length());

    final Matcher wordMatcher = WORD.matcher(text);
    final Matcher numberMatcher = NUMBER.matcher(text);
    final Matcher spaceMatcher = SPACE.matcher(text);

    int offset = 0;
    while (offset < text.length()) {

        wordMatcher.region(offset, text.length());
        numberMatcher.region(offset, text.length());
        spaceMatcher.region(offset, text.length());

        if (wordMatcher.find()) {
            final String word = wordMatcher.group();
            sb.insert(0, reverseCamelCase(word));
            offset = wordMatcher.end();
        } else if (numberMatcher.find()) {
            sb.insert(0, numberMatcher.group());
            offset = numberMatcher.end();
        } else if (spaceMatcher.find()) {
            sb.insert(0, spaceMatcher.group(0));
            offset = spaceMatcher.end();
        } else {
            sb.insert(0, text.charAt(offset++));
        }
    }

    return sb.toString();
}

private static final Pattern CASE_REVERSAL = Pattern
        .compile("(\\p{Lu})(\\p{Ll}*)(\\p{Ll})$");

private static String reverseCamelCase(final String word) {
    final StringBuilder sb = new StringBuilder(word.length());
    final Matcher caseReversalMatcher = CASE_REVERSAL.matcher(word);
    int wordEndOffset = word.length();
    while (wordEndOffset > 0 && caseReversalMatcher.find()) {
        sb.insert(0, caseReversalMatcher.group(3).toUpperCase());
        sb.insert(0, caseReversalMatcher.group(2));
        sb.insert(0, caseReversalMatcher.group(1).toLowerCase());
        wordEndOffset = caseReversalMatcher.start();
        caseReversalMatcher.region(0, wordEndOffset);
    }
    sb.insert(0, word.substring(0, wordEndOffset));
    return sb.toString();
}