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
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:
Compared to your description, this is really short.