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;
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
|
show 10 more comments
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
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 thecontainsmethod.
– 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 callmyLine.contains("2017")on each line.
– Robert Harvey♦
Mar 23 at 19:42
|
show 10 more comments
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
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
java
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 thecontainsmethod.
– 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 callmyLine.contains("2017")on each line.
– Robert Harvey♦
Mar 23 at 19:42
|
show 10 more comments
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 thecontainsmethod.
– 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 callmyLine.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
|
show 10 more comments
5 Answers
5
active
oldest
votes
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).
add a comment |
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);
1
Use StringBuilder for finalString to avoid creating new instances of String object on every concatenation.
– mvmn
Mar 24 at 9:18
add a comment |
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;
add a comment |
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;
add a comment |
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.
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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).
add a comment |
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).
add a comment |
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).
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).
answered Mar 23 at 20:01
Bill NaylorBill Naylor
7117
7117
add a comment |
add a comment |
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);
1
Use StringBuilder for finalString to avoid creating new instances of String object on every concatenation.
– mvmn
Mar 24 at 9:18
add a comment |
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);
1
Use StringBuilder for finalString to avoid creating new instances of String object on every concatenation.
– mvmn
Mar 24 at 9:18
add a comment |
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);
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);
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
add a comment |
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
add a comment |
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;
add a comment |
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;
add a comment |
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;
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;
answered Mar 23 at 20:50
Maran SubburayanMaran Subburayan
8618
8618
add a comment |
add a comment |
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;
add a comment |
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;
add a comment |
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;
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;
answered Mar 24 at 20:42
MndxMndx
12
12
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Mar 25 at 5:02
Abhishek kumarAbhishek kumar
411
411
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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
containsmethod.– 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