-1
String str = "abcdefghijklmnoprqstuvwxyz";
String[] array = new String[str.length()/4 +1];

Array should look like array = {"abcd","efgh","ijkl"...."yz"} after my work. Here is what I have tried:

WORK1:

int strIndex = 0;
int arrayIndex=0;   
for(strIndex=0; strIndex<str.length();strIndex++) {
    array[arrayIndex] += Character.toString(str.charAt(strIndex));  
    if((strIndex % 4 == 0) && (strIndex != 0 ))
    arrayIndex++;
}

======================================================================== WORK2:

String str = "abcdefghijklmnoprqstuvwxyz";
String[] array = new String[str.length()/4 +1];
int start = 0;  // 0->4->8->12..
int end = 4;    // 4->8->12->16...

System.out.println("arraylength:"+array.length);
for(int i=0;i<array.length;i++) {
    array[i] = str.substring(start,end);
    start+=4;
    end+=4;
}

===========================================

WORK1: it gives me the output of abcde fghi jklm nopr qstu vwxy z, which is wrong

WORK2: Because substring() jumps by 4, it will be the cause of Exception when it access the index of 28. Last part should be: (str.substring(24,26));, I can't think of efficient way to handle this.

Any advice will be appreciated.

Purrify
  • 9
  • 2
  • What programming language is this? – Xpleria Oct 12 '17 at 08:35
  • thank you for the advice. I have added the tag "java". I've also checked the possible duplicate post- Although It was one-line, I was having hard time to conceptually understand the code. – Purrify Oct 12 '17 at 15:48

3 Answers3

0

You Need to restrict the Substring end to the strings Maximum lenght:

// pseudocode - you did not supply a tag for the language you are using
str.Substring(start,Math.Min(str.Count,end)) // Math.Min == C#
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

WORK1 should work with a minor change.

Currently you're putting "abcde" into the first array element simply because you're adding the 0th, 1st, 2nd, 3rd and 4th elements. You want to seperate before the 4th element not after. Give this a try:

int strIndex = 0;
int arrayIndex=0;   

for(strIndex=0; strIndex<str.length();strIndex++) {

    if((strIndex % 4 == 0) && (strIndex != 0 ))
                        arrayIndex++;
    array[arrayIndex] += Character.toString(str.charAt(strIndex));   
}

Hopefully this helps. Let me know how you get on!

CodeMonkey123
  • 1,046
  • 13
  • 22
0

Check the below code sniplet, it works fine as you said. Let me know if any issues. (Added a syso just to validate the answer :) )

        String str = "abcdefghijklmnoprqstuvwxyz";
    String[] array = new String[str.length()/4 +1];
    int start = 0;  // 0->4->8->12..
    int end = 4;    // 4->8->12->16...
    int length = str.length();

    System.out.println("arraylength:"+array.length);
    for(int i=0;i<array.length;i++) {

        array[i] = str.substring(start,end);
        start+=4;
        end+=4;

        System.out.println(array[i]);
if(end>length)
   end=length;

    }