-1

substring() method worked good for strings with even length. But for Strings with odd length, subString() did not work as desired. Suppose this Strings:

String myString = "Hell";
String anotherString = "Hello";

I want to divide myString into two parts: "He" and "ll" which worked well with substring() as:

part1 = myString.substring(0, input.length()/2);
part2 = myString.substring(input.length()/2, input.length());

But for anotherString, I want "Hel" and "lo", meaning for even length Strings, I want to roundup the beginIndex to next Index. I tried as below but did not always get the same result.

part1 = anotherString.substring(0, input.length()/2+1);
part2 = anotherString.substring(input.length()/2+1, input.length());

I would like to know if there is any better way to split the Strings as I mentioned using regular expression?

Mirza Obaid
  • 1,707
  • 3
  • 23
  • 35
RSharma
  • 27
  • 1
  • 6
  • 2
    Possible duplicate of [How to split a string into equal parts and store it in a string array](http://stackoverflow.com/questions/26114025/how-to-split-a-string-into-equal-parts-and-store-it-in-a-string-array) – Abdelsalam Shahlol Mar 06 '17 at 04:54
  • "but did not always get the same result" - what do you mean by that? And why would you want to use a regular expression? – Jon Skeet Mar 06 '17 at 04:55
  • Regular expressions are definitely the wrong tool for this job. Please don't fall into the trap of thinking regexes are some sort of Swiss Army Knife that can do all your string processing for you. However, having said that, I don't know how to help you because you haven't shown your code. Please show the code you've tried, any input that isn't in the code, the output you want, and the output you're getting. – ajb Mar 06 '17 at 04:56

1 Answers1

0

I think you can get mid of String by:

int mid = Math.round((float) input.length() / 2);

It work for all case.

dphung duy
  • 19
  • 5