user7160329 user7160329 - 25 days ago 6
Java Question

How to input a "-" between repeating characters in a String Array

I'm trying to use recursion to loop through the String array and input a "-" between repeating characters. Ex: "hello" would output to "hel-lo"

This is my code so far:

Main Class:
public class L6C13PairStar {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
PairStar str = new PairStar();
str.callStars();
}


}

PairStar class:

public class PairStar {

private String[] strs={"hello","xxaayybbzz","aabbaaccdef","jiladdsqss","g","","allstars"};

public void callStars()
{
for (int i=0; i<strs.length; i++)
System.out.println(stars(strs[i]));
System.out.println("*******************************************");
}

public String stars(String str)
{
String temp = null;
if (str.length() > 1)
temp=stars(str.substring(1,str.length()));
if (temp == null && str.length() > 1)
temp=str.substring(1);
if (temp != null)
{
for (int i=0; i<str.length(); i++)
{
int num = 0;
int num1 = 1;

if (str.charAt(num)==str.charAt(num1))
{

str = str.charAt(num) + "-" +str.charAt(num1)+temp;
num++;
num1++;
}
}
return str;
}
return str;
}
}


And outputs to:

hello,
x-xxaayybbzz,
a-aabbaaccdef,
jiladdsqss,
g,
,
allstars
*******************************************


The code only checks if the first two characters are the same. How to I make it continue looking through each part of the array?
Thanks!

Answer
  1. Use a StringBuilder to accumulate your string.
  2. Append the first character of your input to the StringBuilder.
  3. For all other characters in the string:
    1. Check if the current character it is equal to the preceding character: if it is, append a -;
    2. Then, always, append the current character.

I'll let you work out the code for yourself (if you didn't see it in my previous answer...)