match a string in file java - java

I have a problem. I need to use the first row of the txt as my string and then look in the same txt the occurrences and print the number, but I have a problem, for example; if my txt is like: wordwordword and my string is word, it only counts the first word, it does´t print the counter: 3, print the counter: 1. How can I solve this?
Demo.java
import java.io.*;
import java.util.*;
public class Demo {
public static void main(String args[]) throws java.io.IOException {
BufferedReader in = new BufferedReader(new FileReader("c.txt"));
Scanner sc = new Scanner(System.in);
String s1;
s1 = in.readLine();
String Word;
Word = s1;
String line = in.readLine();
int count = 0;
String s[];
do {
s = line.split(" ");
for (int i = 0; i < s.length; i++) {
String a = s[i];
if (a.contains(Word))
count++;
}
line = in.readLine();
} while (line != null);
System.out.println("first line: " + s1);
System.out.print("There are " + count + " occurences of " + Word
+ " in ");
java.io.File file = new java.io.File("c.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
String word = input.nextLine();
System.out.print(word);
}
}
}
txt:
GAGCATAGA
CGAGAGCATATAGGAGCATATCTTGAGCATACCGAGCATATGAGCATAATATACCCGTCCGAGAGCATACACTGAGCATAAAGGAGCATAGAGCATACAACTGAGAATGGAGCATAGAGCATACGGAGCATAAGAGCATAGAGCATAGAGCATACGGAGCATAGAGCATAGAGCATAGCCGATGGGGAGCATACTGTTACGTAGAGCATACGAGCATAGCGCAAGAGCATAAAGAGCATAGAGCATATGAGCATATAGAGCATACGAGCATACAAGATCCGGGGAGCATAGCGAGGTAATAGTCGGAGCATAGAGCATAGAGCATATGAGCATACGGGAGCATAAATGAGCATAAGGAGCATAGAGCATAGAGCATAAGAGCATATCTCGAGCATAAGCGAGCATAGAGCATAAAAATCAATCACGTTGAGCATATGAGCATAAATACTGGAGCATAGATCGAGCATAGTAGAGCATACGAGCATAGAGCATAGGAGCATAAGAGCATATGAGCATATTGAGCATATGAAGGAGCATAAAAATGAGCATAAGGAGCATACCATCGTTGAGCATAATCCGAGCATAGGAGCATAGAATAGAGCATAGACAGGAGTTTTTGGAGCATATGAGCATAGAGCATAGAGCATAGAGCATAGAGCATAGAGCATAGAGCATATTCGAGCATAATTGAGCATATGAGCATAGAGCATATGGAGCATAGGCTGAGCATACCGAGCATAGCAATTAGAGCATAATCCTAGGGAGCATAGGAGCATACGTGAGCATAGCTGAGCATAGAGCATAGAGCATAGTGTTCGAGCATAGAGCATAGAGCATATGAGCATAGAGCATACTTGAGCATATGGTACGAGCATAGGAGCATATAAGGAGGAGCATATCGAGCATAGAGCATAGGCCTGGCCAGAGCATATAACCGAGCATAGGGTTGGAGCATAAGGCCGGAGCATACGAGCATACGAGCATATGAAATGAGCATAATGTGAGCATAGAGCATATCGAGCATATGAGCATAGGAGCATA
in this example with the txt, the program should print the counter= 21

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Match {
public static String TEXT_FILE_LOCATION="input.txt";
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File(TEXT_FILE_LOCATION));
String stringToSearch=in.nextLine();
StringBuffer buffer=new StringBuffer();
for(;in.hasNext();){
buffer.append(in.next());
}
Pattern pattern = Pattern.compile(stringToSearch);
Matcher matcher = pattern.matcher(buffer.toString());
int from = 0;
int count = 0;
while(matcher.find(from)) {
count++;
from = matcher.start() + 1;
}
System.out.println("Number of matches : "+count);
}
}

You can do it by looping through your text then match the string with part of the text.
Here it is:
public static void main(String[] args) {
String word = "word";
String text = "wordwordword";
int count = 0;
for(int i =0 ; i <text.length() ; i++){
for(int j = 0 ; j < word.length();j++){
if((j+i)>=text.length())break;
if(word.charAt(j)!=text.charAt(j+i))break;
if(j==word.length()-1)count++;
}
}
System.out.println(count);//prints 3
}
Also you could use .toCharArray() to get the characters in the string before looping to enhance the performance.
Here is the modified code for that :
public static void main(String[] args) {
char[] word = "word".toCharArray();
char[] text = "wordwordword".toCharArray();
int count = 0;
for(int i =0 ; i <text.length ; i++){
for(int j = 0 ; j < word.length;j++){
if((j+i)>=text.length)break;
if(word[j]!=text[j+i])break;
if(j==word.length-1)count++;
}
}
System.out.println(count);
}

Related

Subsequence words

Suppose this is my .txt file ABCDBCD and I want to use .substring to get this:
ABC BCD CDB DBC BCD
How can I achieve this? I also need to stop the program if a line is shorter than 3 characters.
static void lesFil(String fil, subsekvens allHashMapSubsequences) throws FileNotFoundException{
Scanner scanner = new Scanner(new File("File1.txt"));
String currentLine, subString;
while(scanner.hasNextLine()){
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
for (int i = 0; i + subSize <= currentLine.length(); i++){
subString = currentLinje.substring(i, i + subSize);
subSekStr.putIfAbsent(subString, new subsequence(subString));
}
}
scanner.close();
With a minor changes of your code:
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("C:\\Users\\Public\\File1.txt"));
String currentLine, subString;
int subSize = 3;
while (scanner.hasNextLine()) {
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
if (currentLine.length() < subSize) {
break;
}
for (int i = 0; i + subSize <= currentLine.length(); i++) {
subString = currentLine.substring(i, i + subSize);
System.out.print(subString + " ");
}
System.out.print("\n");
}
scanner.close();
}
This may be what you need
String str = "ABCDBCD";
int substringSize = 3;
String substring;
for(int i=0; i<str.length()-substringSize+1; i++){
substring = str.substring(i, i+substringSize);
System.out.println(substring);
}
import java.util.*;
public class Main
{
public static void main(String[] args) {
String input = "ABCDBCD";
for(int i = 0 ; i < input.length() ; i++) {
if(i < input.length() - 2) {
String temp = input.substring(i,i+3);
System.out.println(temp);
}
}
}
}

Trying two Link classes with Java

I am trying to link two files together and have one count the amount of characters and have the other one give the answer to the character counter. The first file cant have the word that is being given to be displayed as well. How would I go about doing so?
File one
import java.io.*;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String text = "There isn't and exitsing output for that";
try {
FileReader readfile = new FileReader("resources/words.txt");
BufferedReader readbuffer = new BufferedReader(readfile);
Random rn = new Random();
int lines = 0;
while (readbuffer.readLine() != null) {lines++;}
int answer = rn.nextInt(lines);
System.out.println("Line " + (answer + 1));
readfile = new FileReader("resources/words.txt");
readbuffer = new BufferedReader(readfile);
for (int i = 0; i < answer; i++) {
readbuffer.readLine();
}
text = readbuffer.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("The specific Line is: " + text);
}
File two
public class countWords
{
public static void main(String[] args) {
String string = "nose";
int count = 0;
//Counts each character except space
string = string.replaceAll(" ", "");
count = string.length();
//Displays the total number of characters present in the given string
System.out.println("Total number of characters in a string: " + count);
}
}
Figured it out for the first file
import java.io.*;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String text = "There isn't and exitsing output for that";
try {
FileReader readfile = new FileReader("resources/words.txt");
BufferedReader readbuffer = new BufferedReader(readfile);
Random rn = new Random();
int lines = 0;
while (readbuffer.readLine() != null) {lines++;}
int answer = rn.nextInt(lines);
readfile = new FileReader("resources/words.txt");
readbuffer = new BufferedReader(readfile);
for (int i = 0; i < answer; i++) {
readbuffer.readLine();
}
text = readbuffer.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
WordCounter wc = new WordCounter(text);
wc.removeSpaces();
wc.count();
int letters = wc.getCount();
System.out.println("The amount of characters is:" + letters);
}
}
Got the second file
public class WordCounter
{
private final String word;
private int count = 0;
public WordCounter(String word) {
this.word = word;
}
public void removeSpaces() {
word.replaceAll(" ", "");
}
public void count() {
count = word.length();
}
public int getCount() {
return count;
}
}

how can i read and store reattempts?

public class ReadTemps {
public static void main(String[] args) throws IOException {
// TODO code application logic here
// // read KeyWestTemp.txt
// create token1
String token1 = "";
on hover over component 1 change the style
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadTemps{
public static void main(String[] args) throws IOException {
//taking the word to search from keyboard
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the word you want to search: ");
String input = keyboard.nextLine();
//counter for calculating how many times word wrote in line
int counter = 0;
//counter to find which line we are searching
int counterLine = 1;
// // read KeyWestTemp.txt
// create token1
String token1 = "";
// for-each loop for calculating heat index of May - October
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("C:\\KeyWestTemp.txt"));
// Original answer used LinkedList, but probably preferable to use
// ArrayList in most cases
// List<String> temps = new LinkedList<String>();
ArrayList<String> temps = new ArrayList<String>();
// while loop
while (inFile1.hasNext()) {
// find next line
token1 = inFile1.nextLine();
//removing whitespeaces
token1.replaceAll("\\s+","");
//taking all the letters as String
for(int i = 0; i < token1.length(); i++) {
char c = token1.charAt(i);
String s = "" + c;
temps.add(s);
}
//adding a point to find line' end
temps.add("line");
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
//searching on array to find first letter of word
for (int i = 0; i < tempsArray.length; i++) {
String s = temps.get(i);
//if its the end of line time to print
if(s.equals("line")) {
System.out.println("Line" + counterLine + " : " + counter + " occurrence ");
counterLine++;
counter = 0;
}
//if the first letter found need to search rest of the letters
if(s.equalsIgnoreCase("" + input.charAt(0))) {
s = "";
try {
for(int j = i; j < i + input.length(); j++) {
String comp = temps.get(j);
if(comp.equalsIgnoreCase("" + input.charAt(j-i)))
s = s + comp;
}
} catch (IndexOutOfBoundsException e) {
}
//checks if found the word
if(s.equalsIgnoreCase(input))
counter++;
}
}
}
}
This is the code i got for searching char by char for wanted String.
Rather than using inFile1.next();, use inFile1.nextLine(), and don't bother wasting time using a token string.
while (inFile1.hasNext()) {
temps.add(inFile1.nextLine());
}
use BUFFERED READER , it read line by line
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String fullLine;
while ((line = br.readLine()) != null) {
}
}

How to store string values in string array?

I wanted to store name values in String a[] = new String[3];
public static void main(String[] args) throws IOException {
BufferedReader bo = new BufferedReader(new InputStreamReader(System.in));
String name = bo.readLine();
String a[] = new String[3];
}
}
I guess this should suffice:
String a[] = new String[3];
for(int i=0; i<a.length;i++) {
String name = bo.readLine();
a[i] = name;
}
If your name represents names separated by space, try this:
String a[] = name.split(" ");
If you're working from the console I think this is the easiest way for a beginner to tackle user input:
import java.util.Scanner;
public class ReadToStringArray {
private static String[] stringArray = new String[3];
// method that reads user input into the String array
private static void readToArray() {
Scanner scanIn = new Scanner(System.in);
// read from the console 3 times
for (int i = 0; i < stringArray.length; i++) {
System.out.print("Enter a string to put at position " + i + " of the array: ");
stringArray[i] = scanIn.nextLine();
}
scanIn.close();
System.out.println();
}
public static void main(String[] args) {
readToArray();
// print out the stringArray contents
for (int i = 0; i < stringArray.length; i++) {
System.out.println("String at position " + i + " of the array: " + stringArray[i]);
}
}
}
This method uses the java's native Scanner class. You can just copy and paste this and it will work.

Find specific word in text file and count it

someone can help me with code?
How to search in text file any word and count how many it were repeated?
For example test.txt:
hi
hola
hey
hi
bye
hoola
hi
And if I want to know how many times are repeated in test.txt word "Hi" program must say "3 times repeated"
I hope you understood what I want, thank you for answers.
public int countWord(String word, File file) {
int count = 0;
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(word))
count++;
}
return count;
}
HashMap h=new HashMap();
FileInputStream fin=new FileInputStream("d:\\file.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(fin));
String n;
while((n=br.readLine())!=null)
{
if(h.containsKey(n))
{
int i=(Integer)h.get(n);
h.put(n,(i+1));
}
else
h.put(n, 1);
}
now iterate through this map to get the count for each word using each word as a key to the map values
Apache Commons - StringUtils.countMatches()
Use MultiSet collection from google guava library.
Multiset<String> wordsMultiset = HashMultiset.create();
Scanner scanner = new Scanner(fileName);
while (scanner.hasNextLine()) {
wordsMultiset.add(scanner.nextLine());
}
for(Multiset.Entry<String> entry : wordsMultiset ){
System.out.println("Word : "+entry.getElement()+" count -> "+entry.getCount());
}
package File1;
import java.io.BufferedReader;
import java.io.FileReader;
public class CountLineWordsDuplicateWords {
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br =null;
String [] stringArray;
int counLine = 0;
int arrayLength ;
String s="";
String stringLine="";
try{
fr = new FileReader("F:/Line.txt");
br = new BufferedReader(fr);
while((s = br.readLine()) != null){
stringLine = stringLine + s;
stringLine = stringLine + " ";/*Add space*/
counLine ++;
}
System.out.println(stringLine);
stringArray = stringLine.split(" ");
arrayLength = stringArray.length;
System.out.println("The number of Words is "+arrayLength);
/*Duplicate String count code */
for (int i = 0; i < arrayLength; i++) {
int c = 1 ;
for (int j = i+1; j < arrayLength; j++) {
if(stringArray[i].equalsIgnoreCase(stringArray[j])){
c++;
for (int j2 = j; j2 < arrayLength; j2++) {
stringArray[j2] = stringArray[j2+1];
arrayLength = arrayLength - 1;
}
}//End of If block
}//End of Inner for block
System.out.println("The "+stringArray[i]+" present "+c+" times .");
}//End of Outer for block
System.out.println("The number of Line is "+counLine);
System.out.println();
fr.close();
br.close();
}catch (Exception e) {
e.printStackTrace();
}
}//End of main() method
}//End of class CountLineWordsDuplicateWords
package somePackage;
public static void main(String[] args) {
String path = ""; //ADD YOUR PATH HERE
String fileName = "test2.txt";
String testWord = "Macbeth"; //CHANGE THIS IF YOU WANT
int tLen = testWord.length();
int wordCntr = 0;
String file = path + fileName;
boolean check;
try{
FileInputStream fstream = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while((strLine = br.readLine()) != null){
//check to see whether testWord occurs at least once in the line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if(check){
//get the line, and parse its words into a String array
String[] lineWords = strLine.split("\\s+");
for(String w : lineWords){
//first see if the word is as least as long as the testWord
if(w.length() >= tLen){
/*
1) grab the specific word, minus whitespace
2) check to see whether the first part of it having same length
as testWord is equivalent to testWord, ignoring case
*/
String word = w.substring(0,tLen).trim();
if(word.equalsIgnoreCase(testWord)){
wordCntr++;
}
}
}
}
}
System.out.println("total is: " + wordCntr);
//Close the input stream
br.close();
} catch(Exception e){
e.printStackTrace();
}
}
public class Wordcount
{
public static void main(String[] args)
{
int count=0;
String str="hi this is is is line";
String []s1=str.split(" ");
for(int i=0;i<=s1.length-1;i++)
{
if(s1[i].equals("is"))
{
count++;
}
}
System.out.println(count);
}
}
You can read text file line by line. I assume that each line can contain more than one word. For each line, you call:
String[] words = line.split(" ");
for(int i=0; i<words.length; i++){
if(words[i].equalsIgnoreCase(searhedWord))
count++;
}
try using java.util.Scanner.
public int countWords(String w, String fileName) {
int count = 0;
Scanner scanner = new Scanner(inputFile);
scanner.useDelimiter("[^a-zA-Z]"); // non alphabets act as delimeters
String word = scanner.next();
if (word.equalsIgnoreCase(w))
count++;
return count;
}
Try it this way with Pattern and Matcher.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Dem {
public static void main(String[] args){
try {
File f = new File("d://My.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = new String();
while((s=br.readLine())!=null){
s = s + s;
}
int count = 0;
Pattern pat = Pattern.compile("it*");
Matcher mat = pat.matcher(s);
while(mat.find()){
if(mat.find()){
mat.start();
count++;
}
}
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.util.*;
class filedemo
{
public static void main(String ar[])throws Exception
BufferedReader br=new BufferedReader(new FileReader("c:/file.txt"));
System.out.println("enter the string which you search");
Scanner ob=new Scanner(System.in);
String str=ob.next();
String str1="",str2="";
int count=0;
while((str1=br.readLine())!=null)
{
str2 +=str1;
}
int index = str2.indexOf(str);
while (index != -1) {
count++;
str2 = str2.substring(index + 1);
index = str2.indexOf(str);
}
System.out.println("Number of the occures="+count);
}
}
package com.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception{
BufferedReader bf= new BufferedReader(new FileReader("src/test.txt"));
Scanner sc = new Scanner(System.in);
String W=sc.next();
//String regex ="[\\w"+W+"]";
int count=0;
//Pattern p = Pattern.compile();
String line=bf.readLine();
String s[];
do
{
s=line.split(" ");
for(String a:s)
{
if(a.contains(W))
count++;
}
line=bf.readLine();
}while(line!=null);
System.out.println(count);
}
}
public int occurrencesOfHi()
{
String newText = Text.replace("Hi","");
return (Text.length() - newText.length())/2;
}

Categories

Resources