Java分割字符串? [英] Java splitting strings?

查看:51
本文介绍了Java分割字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在出现"时拆分字符串,例如语句test abc.然后,将每个单词中的第一个字母从头到尾移动.我使用

I'm trying split a string when ever a " " occurs, for example the sentence test abc. Then move the first letter in each word from first to last. I got the moving the letter to work on the original string using

String text = JOptionPane.showInputDialog(null,"Skriv in en normal text:");
char firstLetter = text.charAt(0);
normal = text.substring(1,text.length()+0) + firstLetter;

所以我的问题是我将如何分割字符串,然后开始在切割字符串的每个部分中移动字母?

So my question is how would I split the string then start moving the letters around in each part of the cut string?

推荐答案

您不必为此进行 split -tranform-join; replaceAll 可以一步完成.

You don't have to split-tranform-join for this; replaceAll can do this in one step.

    String text = "Skriv in en normal text:";
    text = text.replaceAll("(\\s*)(\\w)(\\w+)", "$1$3$2");
    System.out.println(text);
    // prints "krivS ni ne ormaln extt:"

正则表达式基本上捕获了3个组:

Basically the regex captures 3 groups:

\1 : (\s*) : any optional preceding whitespace
\2 : (\w)  : the head portion of each "word"
\3 : (\w+) : any tail portion of each "word"

然后,由于替换字符串使它变得清晰明了,因此您可以在 \ 2 \ 3 之间切换.

Then, as the replacement string makes it obvious and clear, you switch \2 and \3 around.

因此,应该清楚的是,带有捕获组的 replaceAll 是解决此问题的最佳,最易读的解决方案,但是正则表达式的具体内容取决于问题的规范.请注意,例如,上述正则表达式将 text:转换为 extt:(即,将冒号保留在原处).

So it should be clear that replaceAll with capturing group is the best, most readable solution for this problem, but what that regex is depends on the problem specification. Note that for example, the above regex transforms text: to extt: (i.e. the colon is kept where it is).

以下变体在空格 \ s 上拆分,并对非空格字符 \ S 的任何序列的头/尾重新排序.这应该与您当前的 split(") -transform-join解决方案相同:

The following variation splits on whitespaces \s, and reorders the head/tail of any sequence of non-whitespace characters \S. This should be identical to your current split(" ")-transform-join solution:

    String text = "bob: !@#$ +-";
    text = text.replaceAll("(\\s*)(\\S)(\\S+)", "$1$3$2");
    System.out.println(text);
    // prints "ob:b @#$! -+"

此变体可以对由单词边界 \ b 包围的任何单词字符 \ w + 序列进行切换.如果这是您的需要,那么这是最简单,最易读的解决方案.

This variation do the switch on any word character \w+ sequence surrounded by word boundary \b. If this is what you need, then this is the simplest, most readable solution for the job.

    String text = "abc:def!ghi,jkl mno";
    text = text.replaceAll("\\b(\\w)(\\w+)\\b", "$2$1");
    System.out.println(text);
    // prints "bca:efd!hig,klj nom"

另请参见

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆