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

发布于 2024-12-25 22:34:37 字数 147 浏览 1 评论 0原文

假设我有一个名为 x 的字符串 =“Hello world”。我想以某种方式做到这一点,以便它翻转这两个词并显示“world Hello”。我不太擅长循环或数组,显然是一个初学者。我可以通过分割字符串来实现这一点吗?如果是这样,怎么办?如果没有,我该怎么做?帮助将不胜感激,谢谢!

So say I have a string called x that = "Hello world". I want to somehow make it so that it will flip those two words and instead display "world Hello". I am not very good with loops or arrays and obviously am a beginner. Could I accomplish this somehow by splitting my string? If so, how? If not, how could I do this? Help would be appreciated, thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

空袭的梦i 2025-01-01 22:34:37

1)在空间上将字符串拆分为String数组。

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

2) 使用与数组相反的单词顺序创建新字符串。

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

使用 StringBuilder 而不是串联的奖励点。

1) split string into String array on space.

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

2) Create new string with words in reverse order from array.

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

Bonus points for using a StringBuilder instead of concatenation.

梓梦 2025-01-01 22:34:37
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() ,然后使匹配的条件大写,但保留结果的原始大写等。

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

If you want, you can explode your string as well:

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]);

There are many other ways you can do it too. Be careful for capitalization. You can use .toUpperCase() in your if statements and then make your matching conditionals uppercase, but leave the results with their original capitalization, etc.

仅此而已 2025-01-01 22:34:37

解决方案如下:

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 编写的,也发布在此处:反向词 - GCJ 2010

Here's the solution:

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

The above solution was coded by me, for Google Code Jam and is also blogged here: Reverse Words - GCJ 2010

窝囊感情。 2025-01-01 22:34:37

只需使用这个方法,调用它并传递你想要拆分的字符串

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

Just use this method, call it and pass the string that you want to split out

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;
}
沫离伤花 2025-01-01 22:34:37

根据您的具体要求,您可能需要分割其他形式的空白(制表符、多个空格等):

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 /模式.html

Depending on your exact requirements, you may want to split on other forms of whitespace (tabs, multiple spaces, etc.):

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

If you want to get more complex see the docs for Pattern http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

拥抱影子 2025-01-01 22:34:37

尝试如下操作:

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

Try something as follows:

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

Output:

this is how
习惯成性 2025-01-01 22:34:37

太多了?

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

Too much?

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文