Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

/** * Separates s into two strings, each made of alternating characters * from s

ID: 3725545 • Letter: #

Question

 /**    * Separates s into two strings, each made of alternating characters    * from s, except that runs of the same character are kept together.    * The two strings are concatenated with a space between them to make    * a single returned string. If the given string is empty, the returned     * string is a single space.    * For example,    * <ul>    * <li><code>takeApartPreservingRuns("abcdefa")</code> returns "acea bdf"    * <li><code>takeApartPreservingRuns("aabcccddddefa")</code> returns "aaccccea bddddf"    * </ul>    * @param s    *   any string    * @return    *   pair of strings obtained by taking alternating characters from s,     *   keeping runs of the same character together, concatenated with     *   one space between them into a single string     */   public static String takeApartPreservingRuns(String s)   {     // TODO     return null;   } 

Explanation / Answer

/**

   * Separates s into two strings, each made of alternating characters

   * from s, except that runs of the same character are kept together.

   * The two strings are concatenated with a space between them to make

   * a single returned string. If the given string is empty, the returned

   * string is a single space.

   * For example,

   * <ul>

   * <li><code>takeApartPreservingRuns("abcdefa")</code> returns "acea bdf"

   * <li><code>takeApartPreservingRuns("aabcccddddefa")</code> returns "aaccccea bddddf"

   * </ul>

   * @param s

   * any string

   * @return

   * pair of strings obtained by taking alternating characters from s,

   * keeping runs of the same character together, concatenated with

   * one space between them into a single string

   */

      public static String takeApartPreservingRuns(String s)

      {

      // TODO

          String first = "";

          String second = "";

      

          boolean isFirst = true;

          int i=0;

          while( i<s.length()) {

              if(isFirst) {

                  char c = s.charAt(i);

                  while(i < s.length() && (c == s.charAt(i))) {

                      first = first + c;

                      i++;

                  }

                  isFirst = false;

              }else{

                  char c = s.charAt(i);

                  while(i < s.length() && (c == s.charAt(i))) {

                      second = second + c;

                      i++;

                  }

                  isFirst = true;

              }

          }

      return first + " "+second;

      }