Home > Blockchain >  Convert String to another String
Convert String to another String

Time:10-12

I've got:

String s = "NyffsGeyylB";

I need to change it to:

String result = "N-Yy-Fff-Ffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyy-Yyyyyyyyy-Llllllllll-Bbbbbbbbbbb";

Here is my code so far:

// I use HashMap to count elements
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < s.length(); i  ) {
    map.put(i   1, String.valueOf(s.charAt(i)));
}

// Then I convert it to list
for (Map.Entry<Integer, String> m : map.entrySet()) {
    for (int i = 0; i < m.getKey(); i  ) {
        tempRes.add(m.getValue());
    }
}

// Then I capitalize first letters and add dash
ListIterator<String> iterator = tempRes.listIterator();
while (iterator.hasNext()) {
    iterator.set(iterator.next().toLowerCase());
}

result.add(tempRes.get(0).toUpperCase());
for (int i = 1; i < tempRes.size(); i  ) {
    if (tempRes.get(i).equalsIgnoreCase(tempRes.get(i - 1))) {
        result.add(tempRes.get(i));
    } else {
        result.add("-");
        result.add(tempRes.get(i).toUpperCase());
    }
}

// And finally I add elements from result list to string:
for (int i = 0; i < result.size(); i  ) {
    finalResult  = result.get(i);
}

As a result, I get:

"N-Yy-Fffffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyyyyyyyyyyy-Llllllllll-Bbbbbbbbbbb"

But I need to get:

"N-Yy-Fff-Ffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyy-Yyyyyyyyy-Llllllllll-Bbbbbbbbbbb";

How can I achieve it?

CodePudding user response:

for ( int i = 0 ; i < input.length() ; i  ){
      System.out.print(Character.toUpperCase(input.charAt(i)));
      for (int j = 0; j <= i; j  ){
          System.out.print(Character.toLowerCase(input.charAt(i)));
      }
      if ( i < input.length() - 1)
        System.out.print("-");
  }

CodePudding user response:

public class Main {

    public static void main(String[] args) {
        String s = "NyffsGeyylB";
        StringBuilder res = new StringBuilder();
        char c;
        String s2 = s.toLowerCase();
        for (int i = 0; i < s.length(); i  ) {
            for (int j = 0; j < i   1; j  ) {
                c = s2.charAt(i);
                if (j == 0)
                    res.append(String.valueOf(c).toUpperCase());
                else {
                    res.append(String.valueOf(c));
                }
            }
            res.append("-");
        }
        res.deleteCharAt(res.length() - 1);
        System.out.println(res.toString());
    }
}
  • Related