首页 > 解决方案 > 如何在特定点拆分字符串?

问题描述

我发现很难按照我想要的方式拆分我的字符串,这个平台上的答案都不符合我的要求。

我有字符串:

String s = "1 13 3 1 111 0 18 3";

我想要的是拆分它并分别打印这两个部分。

我想在有空间的地方拆分它,并指定应该拆分的空间。

例如,在空间号 4 处拆分字符串,以打印第一部分:1 13 3 1

第二部分:111 0 18 3

标签: javaandroid-studio

解决方案


对我来说听起来像是算法问题。

这是我的解决方案。这不是最有效的算法,但我这样做是为了让你很容易理解。

    String s = "1 13 3 1 111 0 18 3";
    String[] spitedString = s.split(" "); //Split by white spaces

    int halfIndex = spitedString.length / 2; //Find the center index to divide the string into first and second half.

    String[] firstHalf = Arrays.copyOfRange(spitedString, 0, halfIndex); //First half of String.
    String[] secondHalf = Arrays.copyOfRange(spitedString, halfIndex, spitedString.length - 1); //Second half of String.

    //You could loop through the parts 
    for(String c: firstHalf){
        System.out.println(c);
    }

    //Or put it into one String
    StringBuilder sb = new StringBuilder();
    for(String c: secondHalf){
        sb.append(c); //append string
        sb.append(" "); //and append white space
    }
    System.out.println(sb);

编辑OP 的请求“我可以针对第一个空间,或第五个或任何其他特定条件,假设我有 int target = someIntCalue;”。

当然,逻辑是相同的,只需替换halfIndex为您的targetIndex. 这个想法是halfIndex划分字符串的索引。

如果您有任何问题,请告诉我。谢谢。


推荐阅读