EniGzz
EniGzz

Reputation: 7

Invalid characters in String

I am trying transform a String input that has hyphens and underscores into camel case.

Example:

the-stealth-warrior

should become

theStealthWarrior

I thought I understood completely the problem until I ran into some weird invalid output issues when I run the code.

My code:

public class Application {
    public static void main(String[] args) {
        System.out.println(toCamelCase("the-stealth-warrior"));
    }

    public static String toCamelCase(String s) {
        int sLength = s.length();

        char[] camelCaseWord = new char[sLength];
        int camelCaseIndex = 0;

        for (int i = 0; i < sLength; i++) {
            if (s.charAt(i) == '-' || s.charAt(i) == '_') {
                char upper = Character.toUpperCase(s.charAt(i + 1));
                camelCaseWord[camelCaseIndex] = upper;
                camelCaseIndex++;
                i++;
            } else {
                camelCaseWord[i] = s.charAt(i);
                camelCaseIndex++;
            }
        }
        return new String(camelCaseWord);
    }
}

My output:

theS tealtW  arrior

Does anyone know what could be the issue? Thanks

Upvotes: 0

Views: 604

Answers (2)

Ana
Ana

Reputation: 11

You could also do something like this (I think it is a little less complicated):

   private static void covertToCamelCase(String s) {
    String camelCaseString = "";
    for(int i = 0; i < s.length(); i++){
        if(s.charAt(i) == '_' || s.charAt(i) == '-'){
            
            // if  hyphen or underscore is at the beggining
            if(i == 0) {
                camelCaseString += s.toLowerCase().charAt(i+1);
            }  // if  hyphen or underscore is at the end
            else if(i != s.length()-1) {
                camelCaseString += s.toUpperCase().charAt(i + 1);
            }

            i++;
        }else{
            camelCaseString += s.charAt(i);
        }
    }

    System.out.println(camelCaseString);
}

When you run the code

 public static void main(String[] args) {
    covertToCamelCase("test_test");
    covertToCamelCase("some-new-string-word");
    covertToCamelCase("hyphen-at-end-");
    covertToCamelCase("-hyphen-at-beginning-");
}

The output will be:

testTest
someNewStringWord
hyphenAtEnd
hyphenAtBeginning

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44813

change to

camelCaseWord[camelCaseIndex] = s.charAt(i);

Also you should check this

char upper = Character.toUpperCase(s.charAt(i + 1));

to make sure that it does not exceed then bounds of the String in the case where hyphen or underbar is at the end of the String

Upvotes: 2

Related Questions