-2

I have a string array

String ipist[] = { "817", "818", "819", "820", "821" };

My requirement is if the input is 2

ipist should be

ipist[] = { "817", "818" };

for input 4

ipist[] = { "817", "818", "819", "820" }

that is based on the input need to keep the array elements

Psl
  • 3,830
  • 16
  • 46
  • 84
  • 2
    [`ipist = Arrays.copyOfRange(ipist, 0, input)`](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#copyOfRange-T:A-int-int-) – Andreas Nov 04 '19 at 06:19
  • Thank you. Can u post ur answer.?so that I can accept that – Psl Nov 04 '19 at 06:20
  • 1
    Use `Arrays.copyOfRange`, see [here](https://stackoverflow.com/questions/4439595/how-to-create-a-sub-array-from-another-array-in-java). – bathudaide Nov 04 '19 at 06:21
  • You can use Arrays.copyOfRange or else you can use following code, int j = 0; while(j < 4) { System.out.println(ipist[j]); j++; } – BoomirajP Nov 04 '19 at 06:25

1 Answers1

2

Use Arrays.copyOfRange(T[] original, int from, int to) (Java 6+):

String[] ipist = { "817", "818", "819", "820", "821" };
int input = 3;

ipist = Arrays.copyOfRange(ipist, 0, input);

System.out.println(Arrays.toString(ipist));

Output

[817, 818, 819]
Andreas
  • 154,647
  • 11
  • 152
  • 247