Print all text in-between two characters - java

I want to print a specific part of text from a text file.
For example :
number)street)city)state)country)
I want to print from ) to ) so that any street name or country can go into the text file. What I have done is:
I have tried connecting scanner to the file and creating a while loop with .hasNextLine();
Then creating a String for the whole of the text file String line = textscanner.nextLine();
Then to print out country for example, I would create a substring System.out.print(line.substring(25));
However, this won't work if there are different street or country names in the file. How do I make it so that it will print anything from the ) to )?

You have to take advantage of Java's split() method, which accepts a specified string of text to use as separators/delimiters to words, which are often commas, like in .csv files. I'm going to skip the part about reading the file and just use this string as an example and put the words into an array:
String line = "number)street)city)state)country)";
String[] words = line.split("\\)");
Note in your case you must use double backslashes or the compiler will throw an error saying no matching parentheses.

Related

How to read specific patterns with FileReader in Java

I have a text file that has a repeated pattern after line 14, which does not have a fixed length.
The pattern is as follows:
'
String
String
Int
The apostrophe is used to separate each chunk of data, which I am trying to save into a Hashmap for each type (e.g one hashmap for the first line of each block, etc)
What is the best was to check if there is a block of text (is the apostrophe the best?) and then save the next three lines and continue?

Reading a txt file, and putting each word into an array, without punctuation or numbers

I am wondering how I would read a txt file with Java, and put each word from the txt file into a different bucket in an array, but without punctuation or numbers that are in the file. I'm only interested in storing the words.
So if the text file contained: "25 chickens crossed the road." the program should create an array like {"chickens", "crossed", "the", "road"}
I would like to do this on a fairly large text file. Will I run into any run time issues?
If you could explain it to me like I'm a complete noob, that would be great.
I appreciate it.
Do a .replaceAll(regex, "") which will replace all matching characters with the contents of the second parameter (an empty string in this case). Matching is done with a regular expression.
Second step is to use .split(regex) on your returned string from replaceAll, and split the string on space ( .split(" ") ). This will return an array with all the words separate.
An easy way to write regular expressions is to use http://www.regexr.com
Example code: (not tested)
String oldText = "25 chickens crossed the road.";
String newText = oldText.replaceAll("\!|\.|\?|\d/g","");
String[] strArray = newText.split(" ","");

How to remove first string and comma from a text file

!
I have a text, the content looks like [1,'I am java, and I am happy, I am.....'], I want to remove the first integer and the comma. When I was run the code above, but the result start with last comma: I am......
If you only want to remove commas from a String, you can use String.replaceAll(",",""); If you want to replace them by spaces, use String.replaceAll(","," "):
while ((line = br.readLine()) != null) {
contents.append(line.replaceAll(","," ");
}
Also in your code you seem to split the input, but don't use the result of this operation.
You need to use the indexOfReturns the index within this string of the first occurrence of the specified character, starting the search at the specified index..
lastIndexOf Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
System.out.print(s.substring(s.indexOf(",")+1));
Use this following code as:
System.out.println(line.substring(2));
sub string takes the beginning index as a parameter and splits the string from that index to till the end.
Note that you are using lastIndexOf(). Use indexOf() to get the first index as shown below.
System.out.println(test.substring(line.indexOf(',')+1));
I'm taking your String literially, but you could use String#replaceFirst, for example...
String text = "[1,'I am java, and I am happy, I am.....']";
text = text.replaceFirst("\\[\\d,", "[");
System.out.println(text);
Which outputs...
['I am java, and I am happy, I am.....']
If you want to update the file, you are either going to have to read all the lines into some kind of List (modifying them as you please) and once finished, write the List back to the file (after you've closed it after reading it).
Alternatively, you could write each updated line to a second file, once you're finished, close both files, delete the first and rename the second back in it's place...
Try This code:
String[] s=line.splite(",");
String m="";
for(int i=1;i<s.length;i++)
{
String m=m+s[i];
}
br.append(m);
String input = "[1,'I am java, and I am happy, I am.....']";
//Getting String after first comma
String output = StringUtils.substringAfter(input, ",");
System.out.println("Output:"+output);
//replacing commas;
System.out.println("Final o/p:"+StringUtils.replace(output, ",",""));
You can use methods in StringUtils Class for string manipulations. For using StringUtils methods, you need to import apache-commons-lang.jar file. Using this API you can manipulate many String related methods. For more details, you can see the link
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html

Java check each line of strings from a text file and search if the string exist

Hello Im working on a program to check each line of words from text file and see if they exist
example of execution
Enter a word to search for: taco
Word 'taco' was found.
Enter a word to search for: asd
Word 'asd' was NOT found.
This is the description for assignment
Write a program to read in 100 words from a file. Then, have the user
search for a word until they enter 'quit'. The program will read in up
to 100 words from a file. The file may or may not contain 100 words
but the array should hold up to 100 (if the list does not contain
enough words, fill the rest of the array with empty strings). After
the file is read in, the program will prompt the user for a search
string. The program will then search for the string and tell the user
if the word was found or not. The program will continue to get search
strings from the user until the user enters 'quit'
here is my code so far and is very incomplete
I need advise or suggestion on what else I need to add/fix
thank you!
import java.io.*;
import java.util.Scanner;
public class project2 {
public static void main( String[] args ) throws IOException {
String[] list;
String search = "";
while ( ! search.equals( "quit" ) )
{
System.out.println( "\nEnter a word to search for: " );
Scanner input = new Scanner(System.in);
search = input.next();
Scanner file = new Scanner(new File("words.txt"));
while(file.hasNextLine()){
String str = file.nextLine();
if(str.indexOf("search") != -1){
System.out.println( "Word '" + search + "' was found");}
else System.out.println( "Word '" + search + "' was NOT found");}
}
}
}
Since you did not state a specific question, but seem to be seeking advice, I will point out some flaws I see along with improvements.
Potential flaws:
You are checking each line of the file instead of the entire file. My interpretation of your requirements, and you should verify this, is that you need to determine if the supplied word exists anywhere in the file, not which lines contain it.
The only boundary you split the file on is new line (by virtue of using readLine()). However, I wonder why the requirement uses the word "word". Are you supposed to split on word boundaries? For example, if the file contains the sentence "I will arrive in Tacoma, WA", it will match a search for "Taco", which has nothing to do with the city of Tacoma.
You are rescanning the entire file every time a word is entered. Your requirements did not state whether you need to worry about the file changing during runtime. I would guess no, which means you can probably get away with reading it once and parsing it into an appropriate data structure.
You are doing a linear scan of the file. It would be faster to find all the words, store them into a data structure that is optimized for quick searches.
What is the required / expected behavior for lower case vs. upper case matching? Should "taco" match "Taco"?
My suggestions:
Before entering the input loop, read the contents of the file, line-by-line, and split on whitespace to find "words".
Store each word into a data structure optimized for sub-linear search. I'll leave it as an exercise to you to find an appropriate one. Check the Java collections framework.
If you want to handle this in a case-insensitive way, then lower-case each word prior to adding it to your collection.
In your input loop, do a Collection.contains(o) search on the previously built collection of words to see if it occurs in the file.
If you want to handle this in a case-insensitive way, then lower-case the search term before calling Connection.contains(o).
At the moment, your code checks if the word exists on each line. It needs to check if the word exists in the whole file. To fix this, you can either concatenate the line strings, or use a boolean variable to keep track of whether a word has been found yet.

Reading a line from a text file Java

I am trying to read a line from a file using BufferedReader and Scanner. I can create both of those no problem. What I am looking to do is read one line, count the number of commas in that line, and then go back and grab each individual item. So if the file looked like this:
item1,item2,item3,etc.
item4,item5,item6,etc.
The program would return that there are four commas, and then go back and get one item at a time. It would repeat for the next line. Returning the number of commas is crucial for my program, otherwise, I would just use the Scanner.useDelimiter() method. I also don't know how to return to the beginning of the line to grab each item.
Why not just split the String. The split method accepts a delimiter (regex) as an argument and breaks the String into a String[]. This will eliminate the need to return to the beginning.
String value = "item1,item2,item3";
String[] tokens = value.split(",");
To get the number of commas, just use, tokens.length - 1
String.split() Documentation
Split() can be used to achieve this
eg:
String Line = "item1,item2,item3"
String[] words =Line.split(",");
If you absolutely must know the number of commas, a similar question has already been answered:
Java: How do I count the number of occurrences of a char in a String?

Categories