I’m getting frustrated with this substring function. Here my substring function giving me value first time only. It has been stored first 3 characters in arraylist. Second time it is not able to take other 3 characters and it has been stored ” ” value in arralist.
My code is below :
String mStr= "jklpourtujolkjth";
ArrayList<String> mLst = new ArrayList<String>();
for (int i = 0; i < mStr.length(); i+=3)
{
if ((i + 3) < mStr.length())
{
mLst.add(mStr.substring(i,3));
}
else{
mLst.add(mStr.substring(i));
}
}
Help me with this code. What’s wrong with me?
Thanks,
You probably are assuming that
mStrandmystrare the same. Did you mean to usemStrin both places? (both in the else block and also in the if block)Edit (now that that’s fixed):
You should use
mStr.substring(i,i+3)instead ofmStr.substring(i,3). Substring takes a starting index and end index, but you are assuming it takes a starting index and length.