3
String [] array=new String[7];

array[0]="a";
array[1]="b";
array[2]="c";
array[3]="d";
array[4]="e";
array[5]="f";
array[6]="g";

for (int i=0;i<array.Length;i++){
  if(array[i].equals("b")) {
        // check array from the first one and when it is "b" starts
        // to print the string value till "e"
        System.out.println(array[i]);
    }
    if (array[i].equals("e"))
        break;
}

I have an array of Strings and i want to print the the all the string values when it hits "b" and stop at "e"

Is there anyway i can do that ?

My expected outcome is :

b
c
d
e
7
  • 5
    the way you fill your array is horrible , prefer to use new String[]{"a","b","c", ....} Commented May 18, 2018 at 11:43
  • use loop to fill array elements, and why are you adding elements on the same index? Commented May 18, 2018 at 11:44
  • 1
    also array.Length (L is uppercase) is not valid java Commented May 18, 2018 at 11:45
  • 3
    @JasonWEI I am serious. You should provide demo code that does compile, that people can copy, to maybe reproduce your problem. This site is not a "I have a problem, pls help"-site, so you should also offer us something we can work with, without further interpreting Commented May 18, 2018 at 11:53
  • 1
    @Lino, {"a", "b", "c", ...} (as an array initializer) is less horrible :) Commented May 18, 2018 at 12:17

5 Answers 5

3

A Java-9 solution would be:

Arrays.stream(array)
      .dropWhile(e -> !"b".equals(e))
      .takeWhile(e -> !"f".equals(e))
      .forEach(System.out::println);
Sign up to request clarification or add additional context in comments.

3 Comments

Glorious, but potentially horrible inefficient, due to the extra overhead :)
@Lino dropWhile and takeWhile() are generally cheap operations on sequential pipelines. I wouldn't worry about performance for now until otherwise noticed.
Of course with this small set of data this works like a charm, but it could explode when 1) the datasource is bigger and 2) the conditions never match e.g. by not having the desired element
3
List<String> list = Arrays.asList(array);

list.subList(list.indexOf("b"), list.indexOf("e") + 1)
    .forEach(System.out::println);

*assuming that both "b" and "e" are present in the array (1) and "e" comes after "b" (2).

2 Comments

I was going for this but using String.substring with String.join("", array) but the idea is the same.
creating a new ArrayList<>() is not needed an can be omitted
2

Simply find start and end indexes and iterate over it -

List<String> arrList = Arrays.asList(arr);
int indexOfB = arrList.indexOf("b"); 
int indexOfE = arrList.indexOf("e");
for(int i =indexOfB; i<=indexOfE; i++){
    System.out.println(arr[i]);
}

7 Comments

ArrayUtils is not in the Standard Java language, maybe add a link to apache commons
And I am pretty sure you can get a subset of the array from indexOfB to indexOfE with a library that provided that kind of method. Instead of the loop
that's what I am suggesting (but without the use of a third-party library)
@Andrew, check the updated answer with out using third party.
What is the algorithm used by ArrayUtils.indexOf ? What if you have twice the same value ? It is not precise in the documentation if this return the first occurence or any... PS: That edit is what Andrew did but using two different instance of List.
|
1

You can use a flag to know the first occurence has been found to know if you need to print the current value.

String[] array = {"a", "b", "c", "d", "e", "f", "g"};

boolean toPrint = false;

for (int i = 0; i < array.length; i++) {
    if(array[i].equals("b")) //Find `b`, flag fo printing
        toPrint = true;

    if(toPrint) 
        System.out.println(array[i]);

    if (array[i].equals("e")) //Find `e`, break the loop
        break;
}

This will simply set a boolean to true when the begining occurs and will print every values until the second value is found. Then it will break the loop.

Comments

0

You can find and save index of 'b' in a variable and the same for 'e', after that compare if(indexB <= indexE) and if is true print all from b until to e

EDIT:

public static void main(String[] arg) {

    String[] array = new String[]{"a", "b", "c", "d", "e", "f", "g"};

    bigFor: for (int i = 0; i < array.length; i++) {

        if (array[i].equals("b")) {

            for(int x = i; x < array.length; x++) {

                System.out.println(array[x]);

                if(array[x].equals("e")) {

                    break bigFor;

                }   
            }   
        } 
    }
}

8 Comments

this might be slow, because you have to first iterate the array 2 times, for finding out the indeces, and then again for the printing
I know, but is the most simple and safe method for someone who is beginner.
well it doesn't help you when you learn something "bad" from the beginning, why not do it the correct way from the start?
There is nothing bad. You can improve your knowledge and in time your skill to write efficient code.
Yes it is a bad logic because this logic stops at "this works". Since you are iterating an array to find a first value, keep looking for the second value. Then why using boolean to print based on the values readed. See this solution that used your logic but improved.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.