Search code examples
javastringprefix

How to get all the occurrence character on the prefix of string in java in a simple way?


I have a string like this: '0010'

How can I get the first two zero on that sample string. The rules here is that, I have a variable which hold a character. Then I need to look on the string, if the first character of the string is same with the variable value. I need to keep it and then if the second string matches again, concatenate it and so on. If the first character of the string is not matched with the variable value then it will not store and not look again on the preceding character.

Though I have already solution but I used about 10 lines of codes to do this.

Here is my code:

    String start = "0001";
    String concatVal = "";
    char prefix = '0';

    for(int i = 0; i < start.length(); i++){
        if(start.charAt(i) == prefix){
            concatVal += prefix;
        } else {
            break;
        }
    }
    System.out.println(concatVal);

            //Output
            000

If there is a more simple way to achieve this, please let me know. Thanks


Solution

  • Your code is already very simple. The English description isn't much shorter, so don't worry. With a little bit of rewriting you get:

    public static String prefixOf(String s, char prefix) {
      for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) != prefix) {
          return s.substring(0, i);
        }
      }
      return s;
    }
    

    This definition is only four real lines long:

    1. The method definition is always needed for any algorithm. Doesn't count.
    2. Counts.
    3. Counts.
    4. Counts.
    5. Only a closing brace, which could be omitted.
    6. Only a closing brace, which could be omitted.
    7. Counts.
    8. Every method has to end with a closing brace. Doesn't count.

    Compared to your description, this is really short.