English 中文(简体)
reg reg 半
原标题:regex to split a string in half in java
  • 时间:2010-07-14 20:21:51
  •  标签:
  • java
  • regex

我们需要帮助如何写一下雕塑的雕像。 分裂这样,我们就可以在一半时间内分裂。

感谢。

问题回答

这里没有“obviousregex”模式。 <may> 可上网查阅<编码> String.split,但我只读substring。 类似:

    String s = "12345678abcdefgh";

    final int mid = s.length() / 2;
    String[] parts = {
        s.substring(0, mid),
        s.substring(mid),
    };

    System.out.println(Arrays.toString(parts)); 
    // "[12345678, abcdefgh]"

以上将分成一个比<代码>[0]更长的特性。 如果您需要,则简单地界定了<代码>mid = (s.length () + 1) / 2;。


N-part split

你们也可以做这样的事情,把脚石分成。 N-parts:

static String[] splitN(String s, final int N) {
    final int base = s.length() / N;
    final int remainder = s.length() % N;

    String[] parts = new String[N];
    for (int i = 0; i < N; i++) {
        int length = base + (i < remainder ? 1 : 0);
        parts[i] = s.substring(0, length);
        s = s.substring(length);
    }
    return parts;
}

然后,你可以做到:

    String s = "123456789";

    System.out.println(Arrays.toString(splitN(s, 2)));  
    // "[12345, 6789]"

    System.out.println(Arrays.toString(splitN(s, 3)));
    // "[123, 456, 789]"

    System.out.println(Arrays.toString(splitN(s, 5)));  
    // "[12, 34, 56, 78, 9]"

    System.out.println(Arrays.toString(splitN(s, 10))); 
    // "[1, 2, 3, 4, 5, 6, 7, 8, 9, ]"

请注意,这有利于较早的部分具有额外性,而且当部分数目超过特性数目时,也是有益的。


Appendix

在上述法典中:

  • ?: is the conditional operator, aka the ternary operator.
  • / performs integer division. 1 / 2 == 0.
  • % performs integer remainder operation. 3 % 2 == 1. Also, -1 % 2 == -1.

References

Related questions

确实,你不需要这方面的监管。 Just use substring().

int midpoint = str.length() / 2;
String firstHalf = str.substring(0, midpoint);
String secondHalf = str.substring(midpoint);




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签