【问题标题】:How to split a string into two equally based on the its length如何根据字符串的长度将字符串分成两部分
【发布时间】:2017-07-05 01:09:34
【问题描述】:

我需要根据长度拆分字符串。如果字符串的长度是700,我想将字符串分成两个长度相等的每个 350。我怎么能分开这个。

String text;
int length = text.length();

【问题讨论】:

  • 使用 String.substring(int start_index).
  • 如果字符串有 699 个字符,你会期望什么?
  • 一个字符串中的前 350 个字符和第二个字符串中的其他字符
  • 哎呀...@Phi 打败了我 :) - 删除我的答案。

标签: java


【解决方案1】:

这是你需要的:

String firsthalf = text.subString(0,length/2);
String secondhalf = text.subString(length/2,length);

【讨论】:

    【解决方案2】:

    我还没有评论权限,但这是重复的。这个问题可以从快速谷歌上找到:Splitting a string into two halfs

    int mid = length / 2; //get the middle of the String
    String[] parts = {text.substring(0, mid),text.substring(mid)};
    

    【讨论】:

      【解决方案3】:

      首先你得到String的长度,然后从那个字符串中得到subString

      String string = "Hello World";
      
      int length = string.length();
      
      String firstPart = string.subString(0,length/2);
      String secondPart = string.subString(length/2,length);
      

      就是这样。

      【讨论】:

        猜你喜欢
        • 2017-07-17
        • 1970-01-01
        • 1970-01-01
        • 2013-11-26
        • 2015-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多