【问题标题】:Splitting a string into thirds将字符串分成三份
【发布时间】:2015-12-08 09:15:18
【问题描述】:

我正在做另一个编码测试......只是测试我的一些知识,我遇到了一个高峰。我知道如何将一个字符串分成两半 String.substring blah blah ...但是我如何分成三份?我希望保存到 3 个字符串,“firsthalf”、“secondhalf”和“thirdhalf”有人帮我吗?

(到目前为止的代码):

String text = "abspqrtnf";
    String firsthalf = text.substring(0, text.length() / 3);
    String secondhalf = text.substring(text.length() / 3);
    String thirdhalf = text.substring(text.length() / 3);

【问题讨论】:

    标签: java string split substring


    【解决方案1】:

    继续你开始的方式:

    String text = "abspqrtnf";
    int textLength = text.length();
    String firsthalf = text.substring(0, textLength / 3);
    String secondhalf = text.substring(textLength / 3, text.length() / 3 * 2);
    String thirdhalf = text.substring(text.length() / 3 * 2);
    
    • 下半场需要从上半场结束的地方开始,并且“开始”的时间是前半场的两倍
    • 后半场需要从后半场结束的地方开始并走到最后

    【讨论】:

      【解决方案2】:
      String text = "abspqrtnf";
      String firsthalf = text.substring(0, (text.length() / 3));
      String secondhalf = text.substring(text.length() / 3,(text.length()*2 / 3));
      String thirdhalf = text.substring((text.length()*2 / 3),text.length());
      System.out.println(secondhalf + "   " +firsthalf + "   "+ thirdhalf);
      

      【讨论】:

        【解决方案3】:

        如上所述,如果字符串长度不能被 3 整除(截断或更长的最后一个字符串)并且还要满足小于 3 的输入字符串,您需要决定该怎么做。 建议编写一些单元测试来涵盖这些用例。 下面的一些简单代码作为替代的部分解决方案。

            String input = "abcdefghij";
        
            if( input.length() >= 3 )
            {
                int singleStringLen = input.length() / 3;
                int index = singleStringLen;
        
                System.out.println( input.substring( 0, index ) );
                System.out.println( input.substring( index, (index += singleStringLen) ) );
                // last string maybe longer if input string not divisible by 3
                System.out.println( input.substring( index, input.length() ) );
            }
        

        【讨论】:

          猜你喜欢
          • 2013-11-26
          • 1970-01-01
          • 2015-12-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-04
          • 2016-05-04
          相关资源
          最近更新 更多