-2

So I have a string of chars which I want to cycle through in a for loop. When I reach a certain char that passes a boolean check, I want to take every item in the list after that point and cut off from there. Like below:

for (int i = 0; i < charList.length; i++)
{   if (charList[i] == "a")
    {
        //put every char in charList between i and the end into a new variable
    }
}

What ways are there to do this? Which ones are recommended?

Sam Ofloinn
  • 113
  • 9

3 Answers3

3

The Arrays collection has a copyOfRange() method

for (int i = 0; i < charList.length; i++)
{   if (charList[i] == 'a')
    {
        char[] newCharList = Arrays.copyOfRange(charList,i,charList.length);//put every char in charList between i and the end into a new variable
        //do stuff
        break;
    }
}

If you need to access the new array outside the for loop, make sure to declare it before entering, i.e.

char[] newCharList;
for(...
C.B.
  • 8,096
  • 5
  • 20
  • 34
1

In your if, create a new char[] and then place the characters into it.

char[] substr = new char[charList.length-i];
for (int j = 0; j < charList.length-i; j++) {
    substr[j] = charList[i+j];
}
break; // out of the loop over i

I wrote break but you will probably be returning it, or you would declare substr outside of this scope. The code I wrote is just to give you the idea.

I made a simple ideone for this so you can see it working.

2rs2ts
  • 10,662
  • 10
  • 51
  • 95
0

Use the copyOfRange() method:

char[] charListCopy = Arrays.copyOfRange(charList, i, charList.size());
suavidas
  • 105
  • 3