Extraction of numerals from a string - java

I need to extract the numerals in a given string and store them in a separate array such that each index stores a individual number in the string.
Ex-"15 foxes chases 12 rabbits". I need the numbers 15 and 12 to be stored in a[0] and a[1].
String question=jTextArea1.getText();
String lower=question.toLowerCase();
check(lower);
public void check(String low)
{
int j;
String[] ins={"into","add","Insert"};
String cc=low;
for(int i=0;i<2;i++)
{
String dd=ins[i];
if(cc.contains(dd))
{
j=1;
insert(cc);
break;
}
}}
public void insert(String low)
{
String character = low;
int l=low.length();
int j[]=new int[20];
int m=0;
for(int k=0;k<=2;k++)
{
j[k]=0;
for(int i=0;i<l;i++)
{
char c = character.charAt(i);
if (Character.isDigit(c))
{
String str=Character.toString(c);
j[k]=(j[k]*10)+Integer.parseInt(str);
m++;
}
else if (Character.isLetter(c))
{
if(m>2)
{
break;
}
}}}

Regex is the best option for you.
//Compilation of the regex
Pattern p = Pattern.compile("(\d*)");
// Creation of the search engine
Matcher m = p.matcher("15 foxes chases 12 rabbits");
// Lunching the searching
boolean b = m.matches();
// if any number was found then
if(b) {
// for each found number
for(int i=1; i <= m.groupCount(); i++) {
// Print out the found numbers;
// if you want you can store these number in another array
//since m.group is the one which has the found number(s)
System.out.println("Number " + i + " : " + m.group(i));
}
}
You must import java.util.regex.*;

Assuming you can't use a Collection like a List, I would start by splitting on white space, using a method to count the numbers in that array (with a Pattern on digits), and then build the output array. Something like
public static int getNumberCount(String[] arr) {
int count = 0;
for (String str : arr) {
if (str.matches("\\d+")) {
count++;
}
}
return count;
}
And then use it like
public static void main(String[] args) {
String example = "15 foxes chases 12 rabbits";
String[] arr = example.split("\\s+");
int count = getNumberCount(arr);
int[] a = new int[count];
int pos = 0;
for (String str : arr) {
if (str.matches("\\d+")) {
a[pos++] = Integer.parseInt(str);
}
}
System.out.println(Arrays.toString(a));
}
Output is (as requested)
[15, 12]

To extract numerals from Strings use the following code:
String text = "12 18 100";
String[] n = text.split(" ");
int[] num = n.length;
for (int i =0; i < num.length;i++) {
num[i] = Integer.parseInt(n[i]);
};
All the string numbers in the text will be then integers

I believie it should be
String str = "12 aa 15 155";
Scanner scanner = new Scanner( str );
while( scanner.hasNext() )
{
if( scanner.hasNextInt() )
{
int next = scanner.nextInt();
System.out.println( next );
}
else
{
scanner.next();
}
}
scanner.close();

Related

Java Program to get the sum of integers present in a string considering one of the integers is present in extreme end

I want to get the sum of integers present in the String "abc22gh20fg4". I want my output as 22+20+4=46.
I have written the code as below but it gives 22+20=44. It is not considering the number present in the very end.
public static void main(String[] args) {
String str = "abc22gh20fg4";
String num = "";
int sum = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
num = num + str.charAt(i);
} else {
if (!num.equals("")) {
sum = sum + Integer.parseInt(num);
num = "";
}
}
}
System.out.println(sum);
}
I would go with split instead of deep for loop :
String str = "abc22gh20fg4";
String regex = "[^\\d]+"; // this will extract only digit
String[] strs = str.split(regex);
int sum = Arrays.stream(strs)
.filter(digits -> digits != null && !digits.equals(""))
.mapToInt(Integer::parseInt).sum();
System.out.println(sum);
If you want before java 8
String str = "abc22gh20fg4";
String regex = "[^\\d]+";
String[] strs = str.split(regex); // this will extract only digit
int sum = 0;
for (String digits:strs) { // iterate each digits
if (digits!=null && !digits.equals("")){ // check null or empty
sum += Integer.parseInt(digits); // parse and sum
}
}
System.out.println(sum);
Update:
Your actual problem is when you loop through all the character the last character is number . it exit the loop without sum so you need to check if it is last digit sum it .
public class Test {
public static void main(String[] args) {
String str = "abc22gh20fg4";
String num = "";
int sum = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
num = num + str.charAt(i);
if (i==str.length()-1){ // check if it is last
sum = sum + Integer.parseInt(num);
}
} else {
if (!num.equals("")) {
sum = sum + Integer.parseInt(num);
num = "";
}
}
}
System.out.println(sum);
}
}
You can iterate on integer by using regex:
String str = "abc22gh20fg4";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
int sum = 0;
while (m.find()) {
sum += Integer.parseInt(m.group());
}
System.out.println(sum); // Output: 46
Append this line if character is digit
sum=sum+Integer.parseInt(num); one more time just after for loop
public static void main(String[] args) {
int totalIntegerValue=0;
String currentStringValue="";
String totalStringValue="";
Scanner s = new Scanner(System.in);
String input = s.nextLine();
for(int i=0; i<input.length(); i++) {
if(Character.isDigit(input.charAt(i))) {
currentStringValue+=input.charAt(i);
totalIntegerValue+=Integer.parseInt(currentStringValue);
totalStringValue+=currentStringValue+"+";
}
else
{
currentStringValue="";
}
}
System.out.println(totalStringValue.substring(0, totalStringValue.length()-1)+"="+totalIntegerValue);
s.close();
}

Checking numbers in a string

Notice: I know that there are tons of ways to make this simpler, but it is not allowed. I am bounded to plain, basic java, loops and hand written methods.
Even arrays are not allowed.Regex as well.
Task is to check for numbers in each word of a sentence,find the word with the greatest number which is at the same time POWER OF 3.
I did everything here and it works fine until I enter something like this.
asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125
I receive output 64 instead of 125, because it stops checking when it reaches first number WHICH IS NOT POWER OF 3.
How can I continue the iteration till the end of my sentence and avoid stopping when I reach non power of 3 number ,how to modify this code to achieve that ?
Edit: But if I enter more than one word after the one that FAILS THE CONDITION, it will work just fine.
for instance:
asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125 asdash216
Here is my code:
public class Nine {
static int num(String s) { // method to change string to int
int b = 0;
int o = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char bi = s.charAt(i);
b += (bi - '0') * (int) Math.pow(10, o);
o++;
}
return b;
}
static boolean thirdPow(int a) {
boolean ntrec = false;
if (Math.cbrt(a) % 1 == 0)
ntrec = true;
return ntrec;
}
static int max(int a, int b) {
int max= 0;
if (a > b)
max= a;
else
max= b;
System.out.print(max);
return max;
}
static String search(String r) {
String current= ""; // 23aa64
String currentA= "";
String br = ""; // smjestamo nas broj iz rijeci 23
int bb = 0; // nas pretvoreni string u broj
int p = 0;
for (int i = 0; i < r.length(); i++) {
current+= r.charAt(i);
if (r.charAt(i) == ' ') {
for (int j = 0; j < current.length(); j++) {
while ((int) current.charAt(j) > 47 && (int) current.charAt(j) < 58) {
br += current.charAt(j);
j++;
}
bb = num(br);
System.out.println("Third pow" + thirdPow(bb));
if (thirdPow(bb)) {
p = max(p, bb);
}
br = "";
}
current= "";
}
}
String pp = "" + p;
String finalRes= "";
for (int u = 0; u < r.length(); u++) {
currentA+= r.charAt(u);
if (r.charAt(u) == ' ') {
if (currentA.contains(pp))
finalRes+= currentA;
currentA= "";
}
}
System.out.println(p);
return finalRes;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter sentence: ");
String r = scan.nextLine();
System.out.println("Our string is : " + search(r));
}
}
I am assuming that each word is separated by an empty space and containing non-Integers.
Usage of regular expressions will certainly reduce the code complexity, Let's try this code: -
String input = "asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125";
String[] extractWords = r.split(" "); //extracting each words
int[] numbers = new int[extractWords.length]; // creating an Integer array to store numbers from each word
int i=0;
for(String s : extractWords) {
numbers[i++] = Integer.parseInt(s.replaceAll("\\D+", "")); // extracting numbers
}
Now, the "numbers" array will contain [8, 27, 64, 333, 125]
You can use your logic to find a maximum among them. Hope this helps.
You can just do what I am doing. First split the sentence to chunks of words. I am doing it based on spaces, hence the in.split("\\s+"). Then find the numbers from these words. On these numbers check for the highest number only if it is a power of 3.
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
static boolean isPowOfThree(int num)
{
int temp = (int)Math.pow(num, 1f/3);
return (Math.pow(temp, 3) == num);
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
String in = sc.nextLine();
String[] words = in.split("\\s+");
String maxWord = ""; //init default word
int maxNum = -1; //init default num
for(String word : words)
{
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(word);
while (m.find())
{
String num = m.group();
if(isPowOfThree(Integer.parseInt(num)))
{
if(Integer.parseInt(num) > maxNum)
{
maxNum = Integer.parseInt(num);
maxWord = word;
}
}
}
}
if(maxNum > -1)
{
System.out.println("Word is : " + maxWord);
}
else
{
System.out.println("No word of power 3");
}
}
}
The problem can be solved using \\d+ regular expression with Matcher and Pattern API in Java.
package com.company;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String i = "asdas8 dasjkj278 asdjkj64 asdjk333 asdjkj125";
Matcher matcher = Pattern.compile("\\d+").matcher(i);
List<Integer> numbers = new ArrayList<>();
while (matcher.find()){
numbers.add(Integer.parseInt(matcher.group()));
}
Collections.sort(numbers);
Collections.reverse(numbers);
Integer power3 = 0;
for (Integer n : numbers) {
if (isPowOfThree(n)) {
power3 = n;
break;
}
}
System.out.println(power3);
}
static boolean isPowOfThree(int num) {
int temp = (int)Math.pow(num, 1f/3);
return (Math.pow(temp, 3) == num);
}
}
Upon using \\d+ regular expression we get all the digits in the given string for every iteration of while(matcher.find()). Once we collect all the numbers in the given string, we need to reverse sort the collection. If we iterate over this collection, the first number that we find is the largest number which is a power of 3, since the collection is already sorted in descending order.
Brother use
*string.split(" ");*
to form an array of strings and then iterate through the array and parse the numbers using regex
^[0-9]
or
\d+
and then find the biggest number from the array as simple as that. Brother proceeds step by step then your code will run faster.

Java words reverse

I am new to Java and I found a interesting problem which I wanted to solve. I am trying to code a program that reverses the position of each word of a string. For example, the input string = "HERE AM I", the output string will be "I AM HERE". I have got into it, but it's not working out for me. Could anyone kindly point out the error, and how to fix it, because I am really curious to know what's going wrong. Thanks!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
Got it. Here is my code that implements split and reverse from scratch.
The split function is implemented through iterating through the string, and keeping track of start and end indexes. Once one of the indexes in the string is equivalent to a " ", the program sets the end index to the element behind the space, and adds the previous substring to an ArrayList, then creating a new start index to begin with.
Reverse is very straightforward - you simply iterate from the end of the string to the first element of the string.
Example:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
There is my suggestion :
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
From adding debug output between each method call it's easy to determine that you're successfully reading the input, counting the words, and initializing the array. That means that the problem is in generate().
Problem 1 in generate() (why "HERE" is duplicated in the output): after you add w to your array (when the word is complete) you don't reset w to "", meaning every word has the previous word(s) prepended to it. This is easily seen by adding debug output (or using a debugger) to print the state of ar and w each iteration of the loop.
Problem 2 in generate() (why "I" isn't in the output): there isn't a trailing space in the string, so the condition that adds a word to the array is never met for the last word before the loop terminates at the end of the string. The easy fix is to just add ar[n] = w; after the end of the loop to cover the last word.
I would use the split function and then print from the end of the list to the front.
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
Oops read your comment. Disregard this if it is not what you want.
This has a function that does the same as split, but not the predefined split function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}

Count the number of Occurrences of a Word in a String

I am new to Java Strings the problem is that I want to count the Occurrences of a specific word in a String. Suppose that my String is:
i have a male cat. the color of male cat is Black
Now I dont want to split it as well so I want to search for a word that is "male cat". it occurs two times in my string!
What I am trying is:
int c = 0;
for (int j = 0; j < text.length(); j++) {
if (text.contains("male cat")) {
c += 1;
}
}
System.out.println("counter=" + c);
it gives me 46 counter value! So whats the solution?
You can use the following code:
String in = "i have a male cat. the color of male cat is Black";
int i = 0;
Pattern p = Pattern.compile("male cat");
Matcher m = p.matcher( in );
while (m.find()) {
i++;
}
System.out.println(i); // Prints 2
Demo
What it does?
It matches "male cat".
while(m.find())
indicates, do whatever is given inside the loop while m finds a match.
And I'm incrementing the value of i by i++, so obviously, this gives number of male cat a string has got.
If you just want the count of "male cat" then I would just do it like this:
String str = "i have a male cat. the color of male cat is Black";
int c = str.split("male cat").length - 1;
System.out.println(c);
and if you want to make sure that "female cat" is not matched then use \\b word boundaries in the split regex:
int c = str.split("\\bmale cat\\b").length - 1;
StringUtils in apache commons-lang have CountMatches method to counts the number of occurrences of one String in another.
String input = "i have a male cat. the color of male cat is Black";
int occurance = StringUtils.countMatches(input, "male cat");
System.out.println(occurance);
Java 8 version:
public static long countNumberOfOccurrencesOfWordInString(String msg, String target) {
return Arrays.stream(msg.split("[ ,\\.]")).filter(s -> s.equals(target)).count();
}
Java 8 version.
System.out.println(Pattern.compile("\\bmale cat")
.splitAsStream("i have a male cat. the color of male cat is Black")
.count()-1);
This static method does returns the number of occurrences of a string on another string.
/**
* Returns the number of appearances that a string have on another string.
*
* #param source a string to use as source of the match
* #param sentence a string that is a substring of source
* #return the number of occurrences of sentence on source
*/
public static int numberOfOccurrences(String source, String sentence) {
int occurrences = 0;
if (source.contains(sentence)) {
int withSentenceLength = source.length();
int withoutSentenceLength = source.replace(sentence, "").length();
occurrences = (withSentenceLength - withoutSentenceLength) / sentence.length();
}
return occurrences;
}
Tests:
String source = "Hello World!";
numberOfOccurrences(source, "Hello World!"); // 1
numberOfOccurrences(source, "ello W"); // 1
numberOfOccurrences(source, "l"); // 3
numberOfOccurrences(source, "fun"); // 0
numberOfOccurrences(source, "Hello"); // 1
BTW, the method could be written in one line, awful, but it also works :)
public static int numberOfOccurrences(String source, String sentence) {
return (source.contains(sentence)) ? (source.length() - source.replace(sentence, "").length()) / sentence.length() : 0;
}
using indexOf...
public static int count(String string, String substr) {
int i;
int last = 0;
int count = 0;
do {
i = string.indexOf(substr, last);
if (i != -1) count++;
last = i+substr.length();
} while(i != -1);
return count;
}
public static void main (String[] args ){
System.out.println(count("i have a male cat. the color of male cat is Black", "male cat"));
}
That will show: 2
Another implementation for count(), in just 1 line:
public static int count(String string, String substr) {
return (string.length() - string.replaceAll(substr, "").length()) / substr.length() ;
}
Why not recursive ?
public class CatchTheMaleCat {
private static final String MALE_CAT = "male cat";
static int count = 0;
public static void main(String[] arg){
wordCount("i have a male cat. the color of male cat is Black");
System.out.println(count);
}
private static boolean wordCount(String str){
if(str.contains(MALE_CAT)){
count++;
return wordCount(str.substring(str.indexOf(MALE_CAT)+MALE_CAT.length()));
}
else{
return false;
}
}
}
public class TestWordCount {
public static void main(String[] args) {
int count = numberOfOccurences("Alice", "Alice in wonderland. Alice & chinki are classmates. Chinki is better than Alice.occ");
System.out.println("count : "+count);
}
public static int numberOfOccurences(String findWord, String sentence) {
int length = sentence.length();
int lengthWithoutFindWord = sentence.replace(findWord, "").length();
return (length - lengthWithoutFindWord)/findWord.length();
}
}
This will work
int word_count(String text,String key){
int count=0;
while(text.contains(key)){
count++;
text=text.substring(text.indexOf(key)+key.length());
}
return count;
}
Replace the String that needs to be counted with empty string and then use the length without the string to calculate the number of occurrence.
public int occurrencesOf(String word)
{
int length = text.length();
int lenghtofWord = word.length();
int lengthWithoutWord = text.replace(word, "").length();
return (length - lengthWithoutWord) / lenghtofWord ;
}
Once you find the term you need to remove it from String under process so that it won't resolve the same again, use indexOf() and substring() , you don't need to do contains check length times
The string contains that string all the time when looping through it. You don't want to ++ because what this is doing right now is just getting the length of the string if it contains " "male cat"
You need to indexOf() / substring()
Kind of get what i am saying?
If you find the String you are searching for, you can go on for the length of that string (if in case you search aa in aaaa you consider it 2 times).
int c=0;
String found="male cat";
for(int j=0; j<text.length();j++){
if(text.contains(found)){
c+=1;
j+=found.length()-1;
}
}
System.out.println("counter="+c);
This should be a faster non-regex solution.
(note - Not a Java programmer)
String str = "i have a male cat. the color of male cat is Black";
int found = 0;
int oldndx = 0;
int newndx = 0;
while ( (newndx=str.indexOf("male cat", oldndx)) > -1 )
{
found++;
oldndx = newndx+8;
}
There are so many ways for the occurrence of substring and two of theme are:-
public class Test1 {
public static void main(String args[]) {
String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc a ";
count(st, 0, "a".length());
}
public static void count(String trim, int i, int length) {
if (trim.contains("a")) {
trim = trim.substring(trim.indexOf("a") + length);
count(trim, i + 1, length);
} else {
System.out.println(i);
}
}
public static void countMethod2() {
int index = 0, count = 0;
String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
String subString = "my".toLowerCase();
while (index != -1) {
index = inputString.indexOf(subString, index);
if (index != -1) {
count++;
index += subString.length();
}
}
System.out.print(count);
}}
We can count from many ways for the occurrence of substring:-
public class Test1 {
public static void main(String args[]) {
String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc a ";
count(st, 0, "a".length());
}
public static void count(String trim, int i, int length) {
if (trim.contains("a")) {
trim = trim.substring(trim.indexOf("a") + length);
count(trim, i + 1, length);
} else {
System.out.println(i);
}
}
public static void countMethod2() {
int index = 0, count = 0;
String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
String subString = "my".toLowerCase();
while (index != -1) {
index = inputString.indexOf(subString, index);
if (index != -1) {
count++;
index += subString.length();
}
}
System.out.print(count);
}}
I've got another approach here:
String description = "hello india hello india hello hello india hello";
String textToBeCounted = "hello";
// Split description using "hello", which will return
//string array of words other than hello
String[] words = description.split("hello");
// Get number of characters words other than "hello"
int lengthOfNonMatchingWords = 0;
for (String word : words) {
lengthOfNonMatchingWords += word.length();
}
// Following code gets length of `description` - length of all non-matching
// words and divide it by length of word to be counted
System.out.println("Number of matching words are " +
(description.length() - lengthOfNonMatchingWords) / textToBeCounted.length());
Complete Example here,
package com.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class WordsOccurances {
public static void main(String[] args) {
String sentence = "Java can run on many different operating "
+ "systems. This makes Java platform independent.";
String[] words = sentence.split(" ");
Map<String, Integer> wordsMap = new HashMap<String, Integer>();
for (int i = 0; i<words.length; i++ ) {
if (wordsMap.containsKey(words[i])) {
Integer value = wordsMap.get(words[i]);
wordsMap.put(words[i], value + 1);
} else {
wordsMap.put(words[i], 1);
}
}
/*Now iterate the HashMap to display the word with number
of time occurance */
Iterator it = wordsMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> entryKeyValue = (Map.Entry<String, Integer>) it.next();
System.out.println("Word : "+entryKeyValue.getKey()+", Occurance : "
+entryKeyValue.getValue()+" times");
}
}
}
public class WordCount {
public static void main(String[] args) {
// TODO Auto-generated method stub
String scentence = "This is a treeis isis is is is";
String word = "is";
int wordCount = 0;
for(int i =0;i<scentence.length();i++){
if(word.charAt(0) == scentence.charAt(i)){
if(i>0){
if(scentence.charAt(i-1) == ' '){
if(i+word.length()<scentence.length()){
if(scentence.charAt(i+word.length()) != ' '){
continue;}
}
}
else{
continue;
}
}
int count = 1;
for(int j=1 ; j<word.length();j++){
i++;
if(word.charAt(j) != scentence.charAt(i)){
break;
}
else{
count++;
}
}
if(count == word.length()){
wordCount++;
}
}
}
System.out.println("The word "+ word + " was repeated :" + wordCount);
}
}
Simple solution is here-
Below code uses HashMap as it will maintain keys and values. so here keys will be word and values will be count (occurance of a word in a given string).
public class WordOccurance
{
public static void main(String[] args)
{
HashMap<String, Integer> hm = new HashMap<>();
String str = "avinash pande avinash pande avinash";
//split the word with white space
String words[] = str.split(" ");
for (String word : words)
{
//If already added/present in hashmap then increment the count by 1
if(hm.containsKey(word))
{
hm.put(word, hm.get(word)+1);
}
else //if not added earlier then add with count 1
{
hm.put(word, 1);
}
}
//Iterate over the hashmap
Set<Entry<String, Integer>> entry = hm.entrySet();
for (Entry<String, Integer> entry2 : entry)
{
System.out.println(entry2.getKey() + " "+entry2.getValue());
}
}
}
public int occurrencesOf(String word) {
int length = text.length();
int lenghtofWord = word.length();
int lengthWithoutWord = text.replaceAll(word, "").length();
return (length - lengthWithoutWord) / lenghtofWord ;
}
for scala it's just 1 line
def numTimesOccurrenced(text:String, word:String) =text.split(word).size-1

Java: method to get position of a match in a String?

String match = "hello";
String text = "0123456789hello0123456789";
int position = getPosition(match, text); // should be 10, is there such a method?
The family of methods that does this are:
int indexOf(String str)
indexOf(String str, int fromIndex)
int lastIndexOf(String str)
lastIndexOf(String str, int fromIndex)
Returns the index within this string of the first (or last) occurrence of the specified substring [searching forward (or backward) starting at the specified index].
String text = "0123hello9012hello8901hello7890";
String word = "hello";
System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"
// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
System.out.println(i);
} // prints "4", "13", "22"
// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
System.out.println(i);
} // prints "22", "13", "4"
This works using regex.
String text = "I love you so much";
String wordToFind = "love";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
while (match.find()) {
System.out.println("Found love at index "+ match.start() +" - "+ (match.end()-1));
}
Output :
Found 'love' at index 2 - 5
General Rule :
Regex search left to right, and once the match characters has been used, it cannot be reused.
text.indexOf(match);
See the String javadoc
Finding a single index
As others have said, use text.indexOf(match) to find a single match.
String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10
Finding multiple indexes
Because of #StephenC's comment about code maintainability and my own difficulty in understanding #polygenelubricants' answer, I wanted to find another way to get all the indexes of a match in a text string. The following code (which is modified from this answer) does so:
String text = "0123hello9012hello8901hello7890";
String match = "hello";
int index = text.indexOf(match);
int matchLength = match.length();
while (index >= 0) { // indexOf returns -1 if no match found
System.out.println(index);
index = text.indexOf(match, index + matchLength);
}
You can get all matches in a file simply by assigning inside while-loop, cool:
$ javac MatchTest.java
$ java MatchTest
1
16
31
46
$ cat MatchTest.java
import java.util.*;
import java.io.*;
public class MatchTest {
public static void main(String[] args){
String match = "hello";
String text = "hello0123456789hello0123456789hello1234567890hello3423243423232";
int i =0;
while((i=(text.indexOf(match,i)+1))>0)
System.out.println(i);
}
}
int match_position=text.indexOf(match);
import java.util.StringTokenizer;
public class Occourence {
public static void main(String[] args) {
String key=null,str ="my name noorus my name noorus";
int i=0,tot=0;
StringTokenizer st=new StringTokenizer(str," ");
while(st.hasMoreTokens())
{
tot=tot+1;
key = st.nextToken();
while((i=(str.indexOf(key,i)+1))>0)
{
System.out.println("position of "+key+" "+"is "+(i-1));
}
}
System.out.println("total words present in string "+tot);
}
}
I have some big code but working nicely....
class strDemo
{
public static void main(String args[])
{
String s1=new String("The Ghost of The Arabean Sea");
String s2=new String ("The");
String s6=new String ("ehT");
StringBuffer s3;
StringBuffer s4=new StringBuffer(s1);
StringBuffer s5=new StringBuffer(s2);
char c1[]=new char[30];
char c2[]=new char[5];
char c3[]=new char[5];
s1.getChars(0,28,c1,0);
s2.getChars(0,3,c2,0);
s6.getChars(0,3,c3,0); s3=s4.reverse();
int pf=0,pl=0;
char c5[]=new char[30];
s3.getChars(0,28,c5,0);
for(int i=0;i<(s1.length()-s2.length());i++)
{
int j=0;
if(pf<=1)
{
while (c1[i+j]==c2[j] && j<=s2.length())
{
j++;
System.out.println(s2.length()+" "+j);
if(j>=s2.length())
{
System.out.println("first match of(The) :->"+i);
}
pf=pf+1;
}
}
}
for(int i=0;i<(s3.length()-s6.length()+1);i++)
{
int j=0;
if(pl<=1)
{
while (c5[i+j]==c3[j] && j<=s6.length())
{
j++;
System.out.println(s6.length()+" "+j);
if(j>=s6.length())
{
System.out.println((s3.length()-i-3));
pl=pl+1;
}
}
}
}
}
}
//finding a particular word any where inthe string and printing its index and occurence
class IndOc
{
public static void main(String[] args)
{
String s="this is hyderabad city and this is";
System.out.println("the given string is ");
System.out.println("----------"+s);
char ch[]=s.toCharArray();
System.out.println(" ----word is found at ");
int j=0,noc=0;
for(int i=0;i<ch.length;i++)
{
j=i;
if(ch[i]=='i' && ch[j+1]=='s')
{
System.out.println(" index "+i);
noc++;
}
}
System.out.println("----- no of occurences are "+noc);
}
}
String match = "hello";
String text = "0123456789hello0123456789hello";
int j = 0;
String indxOfmatch = "";
for (int i = -1; i < text.length()+1; i++) {
j = text.indexOf("hello", i);
if (i>=j && j > -1) {
indxOfmatch += text.indexOf("hello", i)+" ";
}
}
System.out.println(indxOfmatch);
If you're going to scan for 'n' matches of the search string, I'd recommend using regular expressions.
They have a steep learning curve, but they'll save you hours when it comes to complex searches.
for multiple occurrence and the character found in string??yes or no
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SubStringtest {
public static void main(String[] args)throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the string");
String str=br.readLine();
System.out.println("enter the character which you want");
CharSequence ch=br.readLine();
boolean bool=str.contains(ch);
System.out.println("the character found is " +bool);
int position=str.indexOf(ch.toString());
while(position>=0){
System.out.println("the index no of character is " +position);
position=str.indexOf(ch.toString(),position+1);
}
}
}
public int NumberWordsInText(String FullText_, String WordToFind_, int[] positions_)
{
int iii1=0;
int iii2=0;
int iii3=0;
while((iii1=(FullText_.indexOf(WordToFind_,iii1)+1))>0){iii2=iii2+1;}
// iii2 is the number of the occurences
if(iii2>0) {
positions_ = new int[iii2];
while ((iii1 = (FullText_.indexOf(WordToFind_, iii1) + 1)) > 0) {
positions_[iii3] = iii1-1;
iii3 = iii3 + 1;
System.out.println("position=" + positions_[iii3 - 1]);
}
}
return iii2;
}
class Main{
public static int string(String str, String str1){
for (int i = 0; i <= str.length() - str1.length(); i++){
int j;
for (j = 0; j < str1.length(); j++) {
if (str1.charAt(j) != str.charAt(i + j)) {
break;
}
}
if (j == str1.length()) {
return i;
}}
return -1;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String str=sc.nextLine();
System.out.println("Enter the Substring");
String str1=sc.nextLine();
System.out.println("The position of the Substring is "+string(str, str1));
}
}

Categories