Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert String to another String

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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?

>Solution :

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("-");
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading