Subsequence words - java

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);
}
}
}
}

Related

Reading a CSV in Java / Jython

Here's a simple problem:
public static double[] stringsToDoubles(String[] inputArr) {
double[] nums = new double[inputArr.length];
for (int i = 0; i < nums.length; i++) {
nums[i] = Double.parseDouble(inputArr[i]);
}
return nums;
}
public static double[][] readPointCloudFile(String filename, int n) {
double[][] points = new double[n][];
String delimiter = ",";
Scanner sc = new Scanner(filename);
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
return points;
}
from jython I import properly, and then call the function as
readPointCloudFile("points.txt", 3)
This gives the error
java.lang.NumberFormatException: java.lang.NumberFormatException: For input string: "points.txt"
You never read from the file. You pass the file name to the Scanner and assume that this string is your csv data, but it is just the filename.
Reading a file can be done as follows when you use Java 8:
import java.nio.file.Files;
import java.nio.file.Paths;
[...]
public static double[][] readPointCloudFile(String filename, int n) {
double[][] points = new double[n][];
String delimiter = ",";
String filecontent = new String(Files.readAllBytes(Paths.get(filename)));
Scanner sc = new Scanner(filecontent);
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
return points;
}
Here's my solution in the spirit of solving your own problems, but I'll give someone else credit because the other solutions are probably better.
public static double[] stringsToDoubles(String[] inputArr){
double[] nums = new double[inputArr.length];
for(int i = 0; i < nums.length; i++){
nums[i] = Double.parseDouble(inputArr[i]);
}
return nums;
}
public static double[][] readPointCloudFile(String filename, int n) throws FileNotFoundException{
double[][] points = new double[n][];
String delimiter = ",";
try{
Scanner sc = new Scanner(new File(filename));
for(int i = 0; i < n; i++){
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
} catch (FileNotFoundException e){
System.err.println(e.getMessage());
} finally {
return points;
}
}

match a string in file 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);
}

Keep getting Exceptions

I am trying to read two files, match them, then print another file as result. But i keep getting this ArrayIndexOutOfBoundsException. I have no idea how to fix it, can someone help me please? Here is my code:
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
class Test{
final static char[][] DIG_CHAR = {{}, {}, {'A', 'B', 'C'}, {'D', 'E', 'F'}, {'G', 'H', 'I'}, {'J', 'K', 'L'}, {'M', 'N', 'O'}, {'P', 'Q', 'R', 'S'}, {'T', 'U', 'V'}, {'W', 'X', 'Y', 'Z'}};
public static void main(String[] args) throws IOException {
String s1 = "telephone.txt";
String s2 = "sample.txt";
Process(s1, s2);
}
public static void Process(String s1, String s2) throws IOException {
int size43 = ThreeCharacters(s2);
int size44 = FourCharacters(s2);
int size47 = SevenCharacters(s2);
String[] WordsOf3 = Store3Words(s2, size43);
String[] WordsOf4 = Store4Words(s2, size44);
String[] WordsOf7 = Store7Words(s2, size47);
String[] s = Char2Dig(WordsOf3);
String[] p = Char2Dig(WordsOf4);
String[] q = Char2Dig(WordsOf7);
Print3(WordsOf3, s, s1);
Print4(WordsOf4, p, s1);
Print7(WordsOf7, q, s1);
}
public static int ThreeCharacters(String s2) throws IOException {
Scanner in = new Scanner(new File(s2));
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
if (in.nextLine().length() == 3) {
count++;
}
}
in.close();
return count;
}
public static int FourCharacters(String s2) throws IOException {
Scanner in = new Scanner(new File(s2));
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
if (in.nextLine().length() == 4) {
count++;
}
}
in.close();
return count;
}
public static int SevenCharacters(String s2) throws IOException {
Scanner in = new Scanner(new File(s2));
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
if(in.nextLine().length() == 7) {
count++;
}
}
in.close();
return count;
}
public static String[] Store3Words(String s2, int size) throws IOException {
//Here is where i keep getting the ArrayIndexOutOfBoundsException, probably same as the next two methods
String[] words = new String[size];
String temp = "";
Scanner in = new Scanner(new File(s2));
int i = 0;
while (in.hasNextLine()) {
temp = in.nextLine();
if (temp.length() == 3) {
words[i] = temp;
i++;
}
}
in.close();
return words;
}
public static String[] Store4Words(String s2, int size) throws IOException {
String[] words = new String[size];
String temp = "";
Scanner in = new Scanner(new File(s2));
int i = 0;
while (in.hasNextLine()) {
temp = in.nextLine();
if (temp.length() == 4) {
words[i] = temp;
i++;
}
}
in.close();
return words;
}
public static String[] Store7Words(String s2, int size) throws IOException {
String[] words = new String[size];
String temp = "";
Scanner in = new Scanner(new File(s2));
int i = 0;
while (in.hasNextLine()) {
temp = in.nextLine();
if (temp.length() == 7) {
words[i] = temp;
i++;
}
}
in.close();
return words;
}
public static String[] Char2Dig(String[] arr) { // ||
String temp = "";
String q = "";
String str = "";
for (int i = 0; i < arr.length; i++) {
temp = arr[i];
str = "";
for (int j = 0; j < temp.length(); j++) {
for (int m = 2; m < DIG_CHAR.length; m++) {
for (int k = 0; k < DIG_CHAR[m].length; k++) {
if (temp.charAt(j) == DIG_CHAR[m][k]) {
q = q + DIG_CHAR[m];
str = str + q;
break;
}
}
if (q == "") {
continue;
}
break;
}
q = "";
}
arr[i] = str;
}
return arr;
}
public static void Print3(String[] WordsOf3, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(4, 7);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf3[i]);
}
}
}
outfile.close();
}
public static void Print4(String[] WordsOf4, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(7, 11);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf4[i]);
}
}
}
outfile.close();
}
public static void Print7(String[] WordsOf7, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(4);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf7[i]);
}
}
}
outfile.close();
}
}
The problem is that you do not count right. You miss the number line of 3, 4 or 7 characters. Let's look at your code, method ThreeCharacters:
public static int ThreeCharacters(String s2) throws IOException {
Scanner in = new Scanner(new File(s2));
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
if (in.nextLine().length() == 3) {
count++;
}
}
in.close();
return count;
}
in.nextLine() reads and skips one line, then if (in.nextLine().length() == 3) again reads and skips another line. At the end, you check only one line over two. The suggestion is to remove the in.nextLine() that is not doing anything, I guess. And if for any reason you put it on purpose, add the same line in Store3Words so that you also process only one line over two. This will solve the ArrayIndexOutOfBoundsException, but you will possibly have other problem in your code, because as beginner, you did not follow the path you are supposed to follow in programming: write one method, test and make sure it is working and move to the next method.
Altogether, I suggest you write a single method to count and a single one to store, your code can become as compact as this:
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
class TestApp{
final static char[][] DIG_CHAR = {{}, {}, {'A', 'B', 'C'}, {'D', 'E', 'F'},
{'G', 'H', 'I'}, {'J', 'K', 'L'}, {'M', 'N', 'O'}, {'P', 'Q', 'R', 'S'},
{'T', 'U', 'V'}, {'W', 'X', 'Y', 'Z'}};
public static void main(String[] args) throws IOException {
String s1 = "telephone.txt";
String s2 = "sample.txt";
Process(s1, s2);
}
public static void Process(String s1, String s2) throws IOException {
int size43 = count(s2, 3);
int size44 = count(s2, 4);
int size47 = count(s2, 7);
/////
System.out.println("lines of 3: "+size43 );
System.out.println("lines of 4: "+size44 );
System.out.println("lines of 7: "+size47 );
/////
String[] WordsOf3 = store(s2, size43, 3);
String[] WordsOf4 = store(s2, size44, 4);
String[] WordsOf7 = store(s2, size47, 7);
/////
System.out.println("lines of 3" );
for(int i = 0; i<size43; i++){
System.out.println( WordsOf3[i] );
}
System.out.println("lines of 4" );
for(int i = 0; i<size44; i++){
System.out.println( WordsOf4[i] );
}
System.out.println("lines of 7" );
for(int i = 0; i<size47; i++){
System.out.println( WordsOf7[i] );
}
/////
String[] s = Char2Dig(WordsOf3);
String[] p = Char2Dig(WordsOf4);
String[] q = Char2Dig(WordsOf7);
Print3(WordsOf3, s, s1);
Print4(WordsOf4, p, s1);
Print7(WordsOf7, q, s1);
}
/** Single method that returns the number of lines of given number of char
* With this single method, no need to write ThreeCharacters, FourCharacters
* and SevenCharacters
*/
public static int count(String fName, int nChar) throws IOException {
Scanner in = new Scanner(new File(fName));
int count = 0;
String tmp; // Note the tmp variable, so that we do not advance twice
while (in.hasNextLine()) {
if (in.nextLine().length() == nChar) {
count++;
}
}
in.close();
return count;
}
/** Single method that returns all the lines of given number of char
* With this single method, no need to write Store3Words, Store4Words
* and Store7Words
*/
public static String[] store(String fName, int size, int nChar) throws IOException {
String[] words = new String[size];
String temp = "";
Scanner in = new Scanner(new File(fName));
int i = 0;
while (in.hasNextLine()) {
temp = in.nextLine();
if (temp.length() == nChar) {
words[i] = temp;
i++;
}
}
in.close();
return words;
}
public static String[] Char2Dig(String[] arr) { // ||
String temp = "";
String q = "";
String str = "";
for (int i = 0; i < arr.length; i++) {
temp = arr[i];
str = "";
for (int j = 0; j < temp.length(); j++) {
for (int m = 2; m < DIG_CHAR.length; m++) {
for (int k = 0; k < DIG_CHAR[m].length; k++) {
if (temp.charAt(j) == DIG_CHAR[m][k]) {
q = q + DIG_CHAR[m];
str = str + q;
break;
}
}
if (q == "") {
continue;
}
break;
}
q = "";
}
arr[i] = str;
}
return arr;
}
public static void Print3(String[] WordsOf3, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(4, 7);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf3[i]);
}
}
}
outfile.close();
}
public static void Print4(String[] WordsOf4, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(7, 11);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf4[i]);
}
}
}
outfile.close();
}
public static void Print7(String[] WordsOf7, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(4);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf7[i]);
}
}
}
outfile.close();
}
}
If I understood the logic behind the Print3, Print4 and Print7 I would have do the same. Also notice that I added some print statement to see what is going on. That is very helpful to see if your code is doing what it is supposed to do.

Copying characters in a string

i am trying to delete every digit from a string and then copy the letter that comes after that digit.
So for example the string 4a2b should output aaaabb.
So far my code looks like this:
Scanner scan= new Scanner(System.in);
String s = scan.nextLine();
String newString = s.replace(" ", "");
newString=newString.replaceAll("\\W+", "");
newString=newString.replaceAll("\\d+", "");
System.out.println(newString);
Is it possible to use regex and replaceAll to do that?
Try,
String newString = "4a2b";
String num = "";
StringBuilder res = new StringBuilder();
for (int i = 0; i < newString.length(); i++) {
char ch = newString.charAt(i);
if (Character.isDigit(ch)) {
num += ch;
} else if (Character.isLetter(ch)) {
if (num.length() > 0) {
for (int j = 0; j < Integer.parseInt(num); j++) {
res.append(ch);
}
}
num="";
}
}
System.out.println(res);
Try this:
public static void main(String[] args)
{
String str = "ae4a2bca";
Matcher m = Pattern.compile("(\\d+)(.)").matcher(str);
StringBuffer sb = new StringBuffer();
while (m.find())
{
m.appendReplacement(sb, times("$2", Integer.parseInt(m.group(1))));
}
m.appendTail(sb);
System.out.println(sb.toString());
}
private static String times(String string, int t)
{
String str = "";
for (int i = 0; i < t; ++i) str += string;
return str;
}

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