I am trying to make an app where you get the input trough the editText component and put it in the string like below:
number = findViewById(R.id.editText2);
newNumber = number.getText().toString();
Now what I want is to replace the string start if a certain condition is met like this:
if (number.getText().toString().substring(0, 1).equals("0")) {
newNumber = newNumber.replaceFirst("06", "3876");
Log.d("TAG", newNumber);
}
I get an error saying that the StringIndexIsOutOfBounds index=2 length=0
I also tried it like this:
if (newNumber.startsWith("06")) {
newNumber = newNumber.replaceFirst("06", "3876");
Log.d("TAG", newNumber);
//Toast.makeText(MainActivity.this, newNumber, Toast.LENGTH_SHORT).show();
}
else {
...
}
I get the else statement when I run this query.
Since I tried this in many combinations, a similar one produces an empty toast. (Can't remember what exactly did it, but it doesn't even matter as it is also not right)
What is wrong in my code? The string is all numbers, but I found it easiest to do the replacements on a string, if you know of a better implementation, be my guest. The input should be 9 numbers, and output should be 11 numbers (I am replacing 06 with 3876 so I get the 2 extra numbers there).
(I have searched SO for similar problems and some attempts were recreations, but none successful)