How to print a substring with only the matching elements of a string?How to generate a random alpha-numeric string?How do I read / convert an InputStream into a String in Java?How do I create a Java string from the contents of a file?How to get an enum value from a string value in Java?How can I convert a stack trace to a string?In Java, how do I check if a string contains a substring (ignoring case)?How to split a string in JavaHow do I convert a String to an int in Java?How to convert a char to a String?Why does this code using random strings print “hello world”?

400–430 degrees Celsius heated bath

Minimum number puzzle!

How to say "invitation for war"?

Are there any nuances between "dismiss" and "ignore"?

Is there a word for pant sleeves?

Connecting circles clockwise in TikZ

How to say "they didn't leave him a penny"?

Eigenvalues of the Laplace-Beltrami operator on a compact Riemannnian manifold

Custom notation table with page reference

How is dynamic resistance of a diode modeled for large voltage variations?

Gambler's Fallacy Dice

Simple Arithmetic Puzzle 7. Or is it?

Parse a C++14 integer literal

Germany rejected my entry to Schengen countries

Is it wise to pay off mortgage with 401k?

Don't understand notation of morphisms in Monoid definition

Why did Nick Fury not hesitate in blowing up the plane he thought was carrying a nuke?

Why use nominative in Coniugatio periphrastica passiva?

Warped chessboard

Good examples of "two is easy, three is hard" in computational sciences

Way of refund if scammed?

How to choose the correct exposure for flower photography?

Salesforce bug enabled "Modify All"

Managing heat dissipation in a magic wand



How to print a substring with only the matching elements of a string?


How to generate a random alpha-numeric string?How do I read / convert an InputStream into a String in Java?How do I create a Java string from the contents of a file?How to get an enum value from a string value in Java?How can I convert a stack trace to a string?In Java, how do I check if a string contains a substring (ignoring case)?How to split a string in JavaHow do I convert a String to an int in Java?How to convert a char to a String?Why does this code using random strings print “hello world”?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















Given a String that lists metadata about a book line by line, how do I print out only the lines that match the data I am looking for?



In order to do this, I've been trying to create substrings for each lines using indexes. The substring starts at the beginning of a line and ends before a "n". I have not seen lists, arrays or bufferedReader yet.



For each substring that I parse through, I check if it contains my pattern. If it does, I add it to a string that only includes my results.



Here would be an example of my list (in french); I'd like to match, for say, all the books written in 2017.



Origine D. Brown 2017 Thriller Policier

Romance et de si belles fiancailles M. H. Clark 2018 thriller policier Romance

La fille du train P. Hawkins 2015 Policier


There is a flaw in how I am doing this and I am stuck with an IndexOutOfBounds exception that I can't figure out. Definitely new in creating algorithms like this.



public static String search() 
String list;

int indexLineStart = 0;
int indexLineEnd = list.indexOf("n");
int indexFinal = list.length()-1;
String listToPrint = "";

while (indexLineStart <= indexFinal)
String listCheck = list.substring(indexLineStart, indexLineEnd);
if (listCheck.contains(dataToMatch))
listToPrint = listToPrint + "n" + listCheck;

indexLineStart = indexLineEnd +1 ;
indexLineEnd = list.indexOf("n", indexLineStart);



return listeToPrint;










share|improve this question



















  • 1





    Can you provide an example of a string and a substring that matches?

    – Robert Harvey
    Mar 23 at 19:30











  • You should also have a look at the contains method.

    – Robert Harvey
    Mar 23 at 19:33












  • Are you able to split the input into lines?

    – Robert Harvey
    Mar 23 at 19:41











  • I think I am, yes.

    – Mndx
    Mar 23 at 19:42











  • Just call myLine.contains("2017") on each line.

    – Robert Harvey
    Mar 23 at 19:42


















0















Given a String that lists metadata about a book line by line, how do I print out only the lines that match the data I am looking for?



In order to do this, I've been trying to create substrings for each lines using indexes. The substring starts at the beginning of a line and ends before a "n". I have not seen lists, arrays or bufferedReader yet.



For each substring that I parse through, I check if it contains my pattern. If it does, I add it to a string that only includes my results.



Here would be an example of my list (in french); I'd like to match, for say, all the books written in 2017.



Origine D. Brown 2017 Thriller Policier

Romance et de si belles fiancailles M. H. Clark 2018 thriller policier Romance

La fille du train P. Hawkins 2015 Policier


There is a flaw in how I am doing this and I am stuck with an IndexOutOfBounds exception that I can't figure out. Definitely new in creating algorithms like this.



public static String search() 
String list;

int indexLineStart = 0;
int indexLineEnd = list.indexOf("n");
int indexFinal = list.length()-1;
String listToPrint = "";

while (indexLineStart <= indexFinal)
String listCheck = list.substring(indexLineStart, indexLineEnd);
if (listCheck.contains(dataToMatch))
listToPrint = listToPrint + "n" + listCheck;

indexLineStart = indexLineEnd +1 ;
indexLineEnd = list.indexOf("n", indexLineStart);



return listeToPrint;










share|improve this question



















  • 1





    Can you provide an example of a string and a substring that matches?

    – Robert Harvey
    Mar 23 at 19:30











  • You should also have a look at the contains method.

    – Robert Harvey
    Mar 23 at 19:33












  • Are you able to split the input into lines?

    – Robert Harvey
    Mar 23 at 19:41











  • I think I am, yes.

    – Mndx
    Mar 23 at 19:42











  • Just call myLine.contains("2017") on each line.

    – Robert Harvey
    Mar 23 at 19:42














0












0








0








Given a String that lists metadata about a book line by line, how do I print out only the lines that match the data I am looking for?



In order to do this, I've been trying to create substrings for each lines using indexes. The substring starts at the beginning of a line and ends before a "n". I have not seen lists, arrays or bufferedReader yet.



For each substring that I parse through, I check if it contains my pattern. If it does, I add it to a string that only includes my results.



Here would be an example of my list (in french); I'd like to match, for say, all the books written in 2017.



Origine D. Brown 2017 Thriller Policier

Romance et de si belles fiancailles M. H. Clark 2018 thriller policier Romance

La fille du train P. Hawkins 2015 Policier


There is a flaw in how I am doing this and I am stuck with an IndexOutOfBounds exception that I can't figure out. Definitely new in creating algorithms like this.



public static String search() 
String list;

int indexLineStart = 0;
int indexLineEnd = list.indexOf("n");
int indexFinal = list.length()-1;
String listToPrint = "";

while (indexLineStart <= indexFinal)
String listCheck = list.substring(indexLineStart, indexLineEnd);
if (listCheck.contains(dataToMatch))
listToPrint = listToPrint + "n" + listCheck;

indexLineStart = indexLineEnd +1 ;
indexLineEnd = list.indexOf("n", indexLineStart);



return listeToPrint;










share|improve this question
















Given a String that lists metadata about a book line by line, how do I print out only the lines that match the data I am looking for?



In order to do this, I've been trying to create substrings for each lines using indexes. The substring starts at the beginning of a line and ends before a "n". I have not seen lists, arrays or bufferedReader yet.



For each substring that I parse through, I check if it contains my pattern. If it does, I add it to a string that only includes my results.



Here would be an example of my list (in french); I'd like to match, for say, all the books written in 2017.



Origine D. Brown 2017 Thriller Policier

Romance et de si belles fiancailles M. H. Clark 2018 thriller policier Romance

La fille du train P. Hawkins 2015 Policier


There is a flaw in how I am doing this and I am stuck with an IndexOutOfBounds exception that I can't figure out. Definitely new in creating algorithms like this.



public static String search() 
String list;

int indexLineStart = 0;
int indexLineEnd = list.indexOf("n");
int indexFinal = list.length()-1;
String listToPrint = "";

while (indexLineStart <= indexFinal)
String listCheck = list.substring(indexLineStart, indexLineEnd);
if (listCheck.contains(dataToMatch))
listToPrint = listToPrint + "n" + listCheck;

indexLineStart = indexLineEnd +1 ;
indexLineEnd = list.indexOf("n", indexLineStart);



return listeToPrint;







java






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 8:23









Zain Arshad

7831315




7831315










asked Mar 23 at 19:29









MndxMndx

12




12







  • 1





    Can you provide an example of a string and a substring that matches?

    – Robert Harvey
    Mar 23 at 19:30











  • You should also have a look at the contains method.

    – Robert Harvey
    Mar 23 at 19:33












  • Are you able to split the input into lines?

    – Robert Harvey
    Mar 23 at 19:41











  • I think I am, yes.

    – Mndx
    Mar 23 at 19:42











  • Just call myLine.contains("2017") on each line.

    – Robert Harvey
    Mar 23 at 19:42













  • 1





    Can you provide an example of a string and a substring that matches?

    – Robert Harvey
    Mar 23 at 19:30











  • You should also have a look at the contains method.

    – Robert Harvey
    Mar 23 at 19:33












  • Are you able to split the input into lines?

    – Robert Harvey
    Mar 23 at 19:41











  • I think I am, yes.

    – Mndx
    Mar 23 at 19:42











  • Just call myLine.contains("2017") on each line.

    – Robert Harvey
    Mar 23 at 19:42








1




1





Can you provide an example of a string and a substring that matches?

– Robert Harvey
Mar 23 at 19:30





Can you provide an example of a string and a substring that matches?

– Robert Harvey
Mar 23 at 19:30













You should also have a look at the contains method.

– Robert Harvey
Mar 23 at 19:33






You should also have a look at the contains method.

– Robert Harvey
Mar 23 at 19:33














Are you able to split the input into lines?

– Robert Harvey
Mar 23 at 19:41





Are you able to split the input into lines?

– Robert Harvey
Mar 23 at 19:41













I think I am, yes.

– Mndx
Mar 23 at 19:42





I think I am, yes.

– Mndx
Mar 23 at 19:42













Just call myLine.contains("2017") on each line.

– Robert Harvey
Mar 23 at 19:42






Just call myLine.contains("2017") on each line.

– Robert Harvey
Mar 23 at 19:42













5 Answers
5






active

oldest

votes


















0














Regardless of the comments about using split() and String[], which do have merit :-)

The IndexOutOfBounds exception I believe is being caused by the second of these two lines:



 indexLineStart = indexLineEnd +1 ;
indexLineEnd = list.indexOf("n", indexLineStart);


You wan't them swapped around (I believe).






share|improve this answer






























    0














    You don't have to make this much complex logic by using String.substring(), what you can use is String.split() and can make an array of your string. At each index is a book, then, you can search for you matching criteria, and add the book to the finalString if it matches your search.



    Working Code:



    public class stackString

    public static void main(String[] args)

    String list = "Origine D. Brown 2017 Thriller Policiern Romance et de si belles fiancailles M. H. Clark 2018 thriller policier Romancen La fille du train P. Hawkins 2015 Policiern";
    String[] listArray = list.split("n"); // make a String Array on each index is new book
    String finalString = ""; // final array to store the books that matches the search
    String matchCondition = "2017";
    for(int i =0; i<listArray.length;i++)
    if(listArray[i].contains(matchCondition))
    finalString += listArray[i]+"n";

    System.out.println(finalString);







    share|improve this answer


















    • 1





      Use StringBuilder for finalString to avoid creating new instances of String object on every concatenation.

      – mvmn
      Mar 24 at 9:18


















    0














    Here is a solution using pattern matching



     public static List<String> search(String input, String keyword)

    Pattern pattern = Pattern.compile(".*" + keyword + ".*");
    Matcher matcher = pattern.matcher(input);
    List<String> linesContainingKeyword = new LinkedList<>();
    while (matcher.find())

    linesContainingKeyword.add(matcher.group());

    return linesContainingKeyword;






    share|improve this answer






























      0














      Since I wasn't allowed to use lists and arrays, I got this to be functional this morning.



       public static String linesWithPattern (String pattern){
      String library;
      library = library + "n"; //Added and end of line at the end of the file to parse through it without problem.
      String substring = "";
      String substringWithPattern = "";
      char endOfLine = 'n';
      int nbrLines = countNbrLines(library, endOfLine); //Method to count number of 'n'
      int lineStart = 0;
      int lineEnd = 0;

      for (int i = 0; i < nbrLines ; i++)
      lineStart = lineEnd;
      if (lineStart == 0)
      lineEnd = library.indexOf('n');
      else if (lineStart != 0)
      lineEnd = library.indexOf('n', (lineEnd + 1));

      substring = library.substring(lineStart, lineEnd);
      if (substring.toLowerCase().contains(motif.toLowerCase()))
      substringWithPattern = substring + substringWithPattern + 'n';

      if (!library.toLowerCase().contains(pattern.toLowerCase()))
      substringWithPattern = "nNO ENTRY FOUND n";



      if (library.toLowerCase().contains(pattern))
      substringWithPattern = "This or these books were found in the library n" +
      "--------------------------" + substringWithPattern;


      return substringWithPattern;





      share|improve this answer






























        0














        The IndexOutOfBounds exception is thrown when the index you are searching for is not in the range of array length. When I went through the code, you are getting this exception because of below line execution where probably the indexLineEnd value is more than the actual length of List if the string variable list is not Null (Since your code doesn't show list variable to be initialized).



        String listCheck = list.substring(indexLineStart, indexLineEnd);



        Please run the application in debug mode to get the exact value that is getting passed to the method to understand why it throwing the exception.



        you need to be careful at calculating the value of indexLineEnd.






        share|improve this answer























          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55317566%2fhow-to-print-a-substring-with-only-the-matching-elements-of-a-string%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          Regardless of the comments about using split() and String[], which do have merit :-)

          The IndexOutOfBounds exception I believe is being caused by the second of these two lines:



           indexLineStart = indexLineEnd +1 ;
          indexLineEnd = list.indexOf("n", indexLineStart);


          You wan't them swapped around (I believe).






          share|improve this answer



























            0














            Regardless of the comments about using split() and String[], which do have merit :-)

            The IndexOutOfBounds exception I believe is being caused by the second of these two lines:



             indexLineStart = indexLineEnd +1 ;
            indexLineEnd = list.indexOf("n", indexLineStart);


            You wan't them swapped around (I believe).






            share|improve this answer

























              0












              0








              0







              Regardless of the comments about using split() and String[], which do have merit :-)

              The IndexOutOfBounds exception I believe is being caused by the second of these two lines:



               indexLineStart = indexLineEnd +1 ;
              indexLineEnd = list.indexOf("n", indexLineStart);


              You wan't them swapped around (I believe).






              share|improve this answer













              Regardless of the comments about using split() and String[], which do have merit :-)

              The IndexOutOfBounds exception I believe is being caused by the second of these two lines:



               indexLineStart = indexLineEnd +1 ;
              indexLineEnd = list.indexOf("n", indexLineStart);


              You wan't them swapped around (I believe).







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Mar 23 at 20:01









              Bill NaylorBill Naylor

              7117




              7117























                  0














                  You don't have to make this much complex logic by using String.substring(), what you can use is String.split() and can make an array of your string. At each index is a book, then, you can search for you matching criteria, and add the book to the finalString if it matches your search.



                  Working Code:



                  public class stackString

                  public static void main(String[] args)

                  String list = "Origine D. Brown 2017 Thriller Policiern Romance et de si belles fiancailles M. H. Clark 2018 thriller policier Romancen La fille du train P. Hawkins 2015 Policiern";
                  String[] listArray = list.split("n"); // make a String Array on each index is new book
                  String finalString = ""; // final array to store the books that matches the search
                  String matchCondition = "2017";
                  for(int i =0; i<listArray.length;i++)
                  if(listArray[i].contains(matchCondition))
                  finalString += listArray[i]+"n";

                  System.out.println(finalString);







                  share|improve this answer


















                  • 1





                    Use StringBuilder for finalString to avoid creating new instances of String object on every concatenation.

                    – mvmn
                    Mar 24 at 9:18















                  0














                  You don't have to make this much complex logic by using String.substring(), what you can use is String.split() and can make an array of your string. At each index is a book, then, you can search for you matching criteria, and add the book to the finalString if it matches your search.



                  Working Code:



                  public class stackString

                  public static void main(String[] args)

                  String list = "Origine D. Brown 2017 Thriller Policiern Romance et de si belles fiancailles M. H. Clark 2018 thriller policier Romancen La fille du train P. Hawkins 2015 Policiern";
                  String[] listArray = list.split("n"); // make a String Array on each index is new book
                  String finalString = ""; // final array to store the books that matches the search
                  String matchCondition = "2017";
                  for(int i =0; i<listArray.length;i++)
                  if(listArray[i].contains(matchCondition))
                  finalString += listArray[i]+"n";

                  System.out.println(finalString);







                  share|improve this answer


















                  • 1





                    Use StringBuilder for finalString to avoid creating new instances of String object on every concatenation.

                    – mvmn
                    Mar 24 at 9:18













                  0












                  0








                  0







                  You don't have to make this much complex logic by using String.substring(), what you can use is String.split() and can make an array of your string. At each index is a book, then, you can search for you matching criteria, and add the book to the finalString if it matches your search.



                  Working Code:



                  public class stackString

                  public static void main(String[] args)

                  String list = "Origine D. Brown 2017 Thriller Policiern Romance et de si belles fiancailles M. H. Clark 2018 thriller policier Romancen La fille du train P. Hawkins 2015 Policiern";
                  String[] listArray = list.split("n"); // make a String Array on each index is new book
                  String finalString = ""; // final array to store the books that matches the search
                  String matchCondition = "2017";
                  for(int i =0; i<listArray.length;i++)
                  if(listArray[i].contains(matchCondition))
                  finalString += listArray[i]+"n";

                  System.out.println(finalString);







                  share|improve this answer













                  You don't have to make this much complex logic by using String.substring(), what you can use is String.split() and can make an array of your string. At each index is a book, then, you can search for you matching criteria, and add the book to the finalString if it matches your search.



                  Working Code:



                  public class stackString

                  public static void main(String[] args)

                  String list = "Origine D. Brown 2017 Thriller Policiern Romance et de si belles fiancailles M. H. Clark 2018 thriller policier Romancen La fille du train P. Hawkins 2015 Policiern";
                  String[] listArray = list.split("n"); // make a String Array on each index is new book
                  String finalString = ""; // final array to store the books that matches the search
                  String matchCondition = "2017";
                  for(int i =0; i<listArray.length;i++)
                  if(listArray[i].contains(matchCondition))
                  finalString += listArray[i]+"n";

                  System.out.println(finalString);








                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 23 at 20:24









                  Zain ArshadZain Arshad

                  7831315




                  7831315







                  • 1





                    Use StringBuilder for finalString to avoid creating new instances of String object on every concatenation.

                    – mvmn
                    Mar 24 at 9:18












                  • 1





                    Use StringBuilder for finalString to avoid creating new instances of String object on every concatenation.

                    – mvmn
                    Mar 24 at 9:18







                  1




                  1





                  Use StringBuilder for finalString to avoid creating new instances of String object on every concatenation.

                  – mvmn
                  Mar 24 at 9:18





                  Use StringBuilder for finalString to avoid creating new instances of String object on every concatenation.

                  – mvmn
                  Mar 24 at 9:18











                  0














                  Here is a solution using pattern matching



                   public static List<String> search(String input, String keyword)

                  Pattern pattern = Pattern.compile(".*" + keyword + ".*");
                  Matcher matcher = pattern.matcher(input);
                  List<String> linesContainingKeyword = new LinkedList<>();
                  while (matcher.find())

                  linesContainingKeyword.add(matcher.group());

                  return linesContainingKeyword;






                  share|improve this answer



























                    0














                    Here is a solution using pattern matching



                     public static List<String> search(String input, String keyword)

                    Pattern pattern = Pattern.compile(".*" + keyword + ".*");
                    Matcher matcher = pattern.matcher(input);
                    List<String> linesContainingKeyword = new LinkedList<>();
                    while (matcher.find())

                    linesContainingKeyword.add(matcher.group());

                    return linesContainingKeyword;






                    share|improve this answer

























                      0












                      0








                      0







                      Here is a solution using pattern matching



                       public static List<String> search(String input, String keyword)

                      Pattern pattern = Pattern.compile(".*" + keyword + ".*");
                      Matcher matcher = pattern.matcher(input);
                      List<String> linesContainingKeyword = new LinkedList<>();
                      while (matcher.find())

                      linesContainingKeyword.add(matcher.group());

                      return linesContainingKeyword;






                      share|improve this answer













                      Here is a solution using pattern matching



                       public static List<String> search(String input, String keyword)

                      Pattern pattern = Pattern.compile(".*" + keyword + ".*");
                      Matcher matcher = pattern.matcher(input);
                      List<String> linesContainingKeyword = new LinkedList<>();
                      while (matcher.find())

                      linesContainingKeyword.add(matcher.group());

                      return linesContainingKeyword;







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Mar 23 at 20:50









                      Maran SubburayanMaran Subburayan

                      8618




                      8618





















                          0














                          Since I wasn't allowed to use lists and arrays, I got this to be functional this morning.



                           public static String linesWithPattern (String pattern){
                          String library;
                          library = library + "n"; //Added and end of line at the end of the file to parse through it without problem.
                          String substring = "";
                          String substringWithPattern = "";
                          char endOfLine = 'n';
                          int nbrLines = countNbrLines(library, endOfLine); //Method to count number of 'n'
                          int lineStart = 0;
                          int lineEnd = 0;

                          for (int i = 0; i < nbrLines ; i++)
                          lineStart = lineEnd;
                          if (lineStart == 0)
                          lineEnd = library.indexOf('n');
                          else if (lineStart != 0)
                          lineEnd = library.indexOf('n', (lineEnd + 1));

                          substring = library.substring(lineStart, lineEnd);
                          if (substring.toLowerCase().contains(motif.toLowerCase()))
                          substringWithPattern = substring + substringWithPattern + 'n';

                          if (!library.toLowerCase().contains(pattern.toLowerCase()))
                          substringWithPattern = "nNO ENTRY FOUND n";



                          if (library.toLowerCase().contains(pattern))
                          substringWithPattern = "This or these books were found in the library n" +
                          "--------------------------" + substringWithPattern;


                          return substringWithPattern;





                          share|improve this answer



























                            0














                            Since I wasn't allowed to use lists and arrays, I got this to be functional this morning.



                             public static String linesWithPattern (String pattern){
                            String library;
                            library = library + "n"; //Added and end of line at the end of the file to parse through it without problem.
                            String substring = "";
                            String substringWithPattern = "";
                            char endOfLine = 'n';
                            int nbrLines = countNbrLines(library, endOfLine); //Method to count number of 'n'
                            int lineStart = 0;
                            int lineEnd = 0;

                            for (int i = 0; i < nbrLines ; i++)
                            lineStart = lineEnd;
                            if (lineStart == 0)
                            lineEnd = library.indexOf('n');
                            else if (lineStart != 0)
                            lineEnd = library.indexOf('n', (lineEnd + 1));

                            substring = library.substring(lineStart, lineEnd);
                            if (substring.toLowerCase().contains(motif.toLowerCase()))
                            substringWithPattern = substring + substringWithPattern + 'n';

                            if (!library.toLowerCase().contains(pattern.toLowerCase()))
                            substringWithPattern = "nNO ENTRY FOUND n";



                            if (library.toLowerCase().contains(pattern))
                            substringWithPattern = "This or these books were found in the library n" +
                            "--------------------------" + substringWithPattern;


                            return substringWithPattern;





                            share|improve this answer

























                              0












                              0








                              0







                              Since I wasn't allowed to use lists and arrays, I got this to be functional this morning.



                               public static String linesWithPattern (String pattern){
                              String library;
                              library = library + "n"; //Added and end of line at the end of the file to parse through it without problem.
                              String substring = "";
                              String substringWithPattern = "";
                              char endOfLine = 'n';
                              int nbrLines = countNbrLines(library, endOfLine); //Method to count number of 'n'
                              int lineStart = 0;
                              int lineEnd = 0;

                              for (int i = 0; i < nbrLines ; i++)
                              lineStart = lineEnd;
                              if (lineStart == 0)
                              lineEnd = library.indexOf('n');
                              else if (lineStart != 0)
                              lineEnd = library.indexOf('n', (lineEnd + 1));

                              substring = library.substring(lineStart, lineEnd);
                              if (substring.toLowerCase().contains(motif.toLowerCase()))
                              substringWithPattern = substring + substringWithPattern + 'n';

                              if (!library.toLowerCase().contains(pattern.toLowerCase()))
                              substringWithPattern = "nNO ENTRY FOUND n";



                              if (library.toLowerCase().contains(pattern))
                              substringWithPattern = "This or these books were found in the library n" +
                              "--------------------------" + substringWithPattern;


                              return substringWithPattern;





                              share|improve this answer













                              Since I wasn't allowed to use lists and arrays, I got this to be functional this morning.



                               public static String linesWithPattern (String pattern){
                              String library;
                              library = library + "n"; //Added and end of line at the end of the file to parse through it without problem.
                              String substring = "";
                              String substringWithPattern = "";
                              char endOfLine = 'n';
                              int nbrLines = countNbrLines(library, endOfLine); //Method to count number of 'n'
                              int lineStart = 0;
                              int lineEnd = 0;

                              for (int i = 0; i < nbrLines ; i++)
                              lineStart = lineEnd;
                              if (lineStart == 0)
                              lineEnd = library.indexOf('n');
                              else if (lineStart != 0)
                              lineEnd = library.indexOf('n', (lineEnd + 1));

                              substring = library.substring(lineStart, lineEnd);
                              if (substring.toLowerCase().contains(motif.toLowerCase()))
                              substringWithPattern = substring + substringWithPattern + 'n';

                              if (!library.toLowerCase().contains(pattern.toLowerCase()))
                              substringWithPattern = "nNO ENTRY FOUND n";



                              if (library.toLowerCase().contains(pattern))
                              substringWithPattern = "This or these books were found in the library n" +
                              "--------------------------" + substringWithPattern;


                              return substringWithPattern;






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Mar 24 at 20:42









                              MndxMndx

                              12




                              12





















                                  0














                                  The IndexOutOfBounds exception is thrown when the index you are searching for is not in the range of array length. When I went through the code, you are getting this exception because of below line execution where probably the indexLineEnd value is more than the actual length of List if the string variable list is not Null (Since your code doesn't show list variable to be initialized).



                                  String listCheck = list.substring(indexLineStart, indexLineEnd);



                                  Please run the application in debug mode to get the exact value that is getting passed to the method to understand why it throwing the exception.



                                  you need to be careful at calculating the value of indexLineEnd.






                                  share|improve this answer



























                                    0














                                    The IndexOutOfBounds exception is thrown when the index you are searching for is not in the range of array length. When I went through the code, you are getting this exception because of below line execution where probably the indexLineEnd value is more than the actual length of List if the string variable list is not Null (Since your code doesn't show list variable to be initialized).



                                    String listCheck = list.substring(indexLineStart, indexLineEnd);



                                    Please run the application in debug mode to get the exact value that is getting passed to the method to understand why it throwing the exception.



                                    you need to be careful at calculating the value of indexLineEnd.






                                    share|improve this answer

























                                      0












                                      0








                                      0







                                      The IndexOutOfBounds exception is thrown when the index you are searching for is not in the range of array length. When I went through the code, you are getting this exception because of below line execution where probably the indexLineEnd value is more than the actual length of List if the string variable list is not Null (Since your code doesn't show list variable to be initialized).



                                      String listCheck = list.substring(indexLineStart, indexLineEnd);



                                      Please run the application in debug mode to get the exact value that is getting passed to the method to understand why it throwing the exception.



                                      you need to be careful at calculating the value of indexLineEnd.






                                      share|improve this answer













                                      The IndexOutOfBounds exception is thrown when the index you are searching for is not in the range of array length. When I went through the code, you are getting this exception because of below line execution where probably the indexLineEnd value is more than the actual length of List if the string variable list is not Null (Since your code doesn't show list variable to be initialized).



                                      String listCheck = list.substring(indexLineStart, indexLineEnd);



                                      Please run the application in debug mode to get the exact value that is getting passed to the method to understand why it throwing the exception.



                                      you need to be careful at calculating the value of indexLineEnd.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Mar 25 at 5:02









                                      Abhishek kumarAbhishek kumar

                                      411




                                      411



























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55317566%2fhow-to-print-a-substring-with-only-the-matching-elements-of-a-string%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                                          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해