Getting the number of occurrences of one string in another string - java

I need to input a two strings, with the first one being any word and the second string being a part of the previous string and i need to output the number of times string number two occurs. So for instance:String 1 = CATSATONTHEMAT String 2 = AT. Output would be 3 because AT occurs three times in CATSATONTHEMAT. Here is my code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.indexOf(word9);
System.out.println(occurences);
}
It outputs 1 when I use this code.

Interesting solution:
public static int countOccurrences(String main, String sub) {
return (main.length() - main.replace(sub, "").length()) / sub.length();
}
Basically what we're doing here is subtracting the length of main from the length of the string resulting from deleting all instances of sub in main - we then divide this number by the length of sub to determine how many occurrences of sub were removed, giving us our answer.
So in the end you would have something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurrences = countOccurrences(word8, word9);
System.out.println(occurrences);
sc.close();
}

You could also try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.nextLine();
String word9 = sc.nextLine();
int index = word8.indexOf(word9);
sc.close();
int occurrences = 0;
while (index != -1) {
occurrences++;
word8 = word8.substring(index + 1);
index = word8.indexOf(word9);
}
System.out.println("No of " + word9 + " in the input is : " + occurrences);
}

Why no one posts the most obvious and fast solution?
int occurrences(String str, String substr) {
int occurrences = 0;
int index = str.indexOf(substr);
while (index != -1) {
occurrences++;
index = str.indexOf(substr, index + 1);
}
return occurrences;
}

Another option:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.split(word9).length;
if (word8.startsWith(word9)) occurences++;
if (word8.endsWith(word9)) occurences++;
System.out.println(occurences);
sc.close();
}
The startsWith and endsWith are required because split() omits trailing empty strings.

Related

Java program to check spanish ID letter

the user has to type their ID, including the letter (example 19452100G) the program has to say if the letter is correct or not. If the letter is not correct, the program will write the correct one.
Scanner sc = new Scanner(System.in);
System.out.print("Enter ID number: ");
int numID = sc.nextInt();
System.out.printf("letter corresponde %d is %c", numID, calculateLetter(numID));
sc.close();
}
private static char calculateLetter(int id){
String caracteres="TRWAGMYFPDXBNJZSQVHLCKE";
int resto = id%23;
return caracteres.charAt(resto);
}
#SuppressWarnings("unused")
private static char calcularLetraArray(int dni){
char caracteres[] = {'T','R','W','A','G','M','Y','F','P','D','X','B','N','J','Z','S','Q','V','H','L','C','K','E'};
int resto = id%23;
return caracteres[resto];
}
}
1.You are storing a String variable inside a Integer Variable.
2.Also there is no need of two methods for checking letter and correcting the letter
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter ID number: ");
String numID = sc.nextLine();
char letter_corresponde = calculateLetter(numID);
System.out.printf("letter corresponde %s is %c \n", numID, letter_corresponde);
if (numID.charAt(numID.length()-1) == letter_corresponde)
System.out.println("letter_corresponde matches no need to correct it");
else {
System.out.println("Correcting the letter_corresponde");
numID = numID.substring(0,numID.length()-1) + letter_corresponde;
System.out.println(numID);
}
}
public static char calculateLetter(String numID){
String caracteres="TRWAGMYFPDXBNJZSQVHLCKE";
int id = Integer.parseInt(numID.substring(0,numID.length()-2));
int resto = id%23;
return caracteres.charAt(resto);
}

Java Splitting Strings and Applying A Method

I'm working on a code in java that will swap a random letter inside of a word with another random letter within that word.
I need to apply this code to an entire string. The issue I'm having is my code can't identify white space and therefore runs the method for once per string instead of once per word. How can I split the input string and apply the method to each word individually. Here's what I have so far.
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args {
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
System.out.print(scramble(word));
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
Check the inline comments:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
//Split your input phrase
String[] wordsArray = word.split(" ");
//For each word in the phrase call your scramble function
// and print the output plus a space
for (String s : wordsArray){
System.out.print(scramble(s) + " ");
}
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
As destriped in teh String.split(); you can define a regrex for instance " " and then a return array of String[] for all substrings split on the input is returned
see String split
example
String in = "hello world";
String[] splitIn = in.split(" ");
The same way you can test for other things such as "," "." ";" ":" etc

ask the user for input (a sentence) and print out the longest word of that sentence

How do I have this program ask the user for input (a sentence) and print out the longest word of that sentence.
package projectOne;
import java.util.Scanner;
public class LongestWord {
//Scanner keyboard = new Scanner(System.in);
//System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
static String actualstring = keyboard.nextLine();
static String[] splitstring = actualstring.split(" ");
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
//String[] splitstring = actualstring.split(" ");
LongWord();
}
public static void LongWord() {
String longword = "";
for (int i=0; i<=splitstring.length-1; i++){
if (longword.length()<splitstring[i].length())
longword = splitstring[i];
}
System.out.println(longword);
int replyLength = longword.length();
System.out.println(replyLength);
if (replyLength == 3)
System.out.println("Hmmm tell me more about "+longword+" please");
else if (replyLength == 4)
System.out.println("Why do you feel "+longword+" is important?");
else if (replyLength == 5)
System.out.println("How does "+longword+" affect you?");
else if (replyLength > 5)
System.out.println("We seem to be making great progress with "+longword);
else
System.out.println("Is there something else you would like to discuss?");
}
}
I don't think you quite understand how methods work. In your main you should prompt the user for the line they'd like to enter and then you should read the entire line intro a String using the Scanner.nextLine() method and then you should pass said String into your longWord method for processing.
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
String sentence = keyboard.nextLine();
longWord(sentence);
}
public static void longWord(String sentence) {
//Process and print the longest word using the passed in String param
//Splitting, looping, comparisons, output
}
Try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String maxword = null;
str = str + ' ';
int l = str.length();
String word = "";
int maxlength = 0;
for (int i = 0; i < l; i++) {
word = word + str.charAt(i);
if (str.charAt(i + 1) == ' ') {
if (word.length() > maxlength) {
maxword = new String(word);
maxlength = word.length();
}
word = "";
i++;
}
}
System.out.println("Longest Word: " + maxword);
}

Java program involving substring() and charAt() methods

My program is supposed to print out the initials of the name and print the last name.
Eg. if the name entered is Mohan Das Karamchand Gandhi, the output must be MDK Gandhi. Although I get a "String index out of range" exception.
import java.util.Scanner;
public class name {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String w=s.nextLine();
int l=w.length();
char ch=0; int space=0;int spacel = 0;
for(int i=0;i<l;i++){
ch=w.charAt(i);
if(ch==32||ch==' '){
space+=1;
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
}
}
System.out.println(w.substring(spacel,l+1));
}
This is the culprit:
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
When i is equal to l - 1, then space1 is going to be equal to l or w.length(), which is beyond the end of the string.
This can be easily achieved using String's split() method or using StringTokenizer.
First split string using space as delimiter. Then according to your format last string would be Last Name and iterate over other string objects to get initial characters.
String name = "Mohan Das Karamchand Gandhi";
String broken[] = name.split(" ");
int len = broken.length;
char initials[] = new char[len-1];
for(int i=0;i<len-1;i++) {
initials[i] = broken[i].charAt(0);
}
String finalAns = new String(initials)+" "+broken[len-1];
import java.util.Scanner;
public class name
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String w=s.nextLine();
int l=w.length();
char ch=0; int space=0;int spacel = 0;
System.out.print(w.charAt(0) + " ");
for(int i=0;i<l;i++)
{
ch=w.charAt(i);
if(ch==32||ch==' ')
{
space+=1;
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
}
}
System.out.println("\b\b"+w.substring(spacel,l));
}
}

Removing inserted numbers from a String in java

Ok, so i have created a program that defines if the inserted word is a palindrome or not.
But i need help on removing numbers that where to be inserted in the string.
import java.util.*;
import java.util.Scanner;
class Palindrome
{
public static void main(String args[])
{
String reverse = "";
Scanner scan = new Scanner(System.in);
System.out.print("Type a sentence and press enter: ");
String input = scan.nextLine();
// use regex to remove the punctuation and spaces
String Input = input.replaceAll("\\W", " ");
System.out.println(Input);
int length = input.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse.replaceAll("\\W", "") + input.charAt(i);
System.out.println(reverse);
if (input.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
If you want to remove digits, try input.replaceAll("[0-9]","")
Try this........
public class T1 {
public static void main(String[] args){
String s = "1234ajhdhols233adfjal";
String[] arr = s.split("\\d");
String sx = new String();
for(String x : arr){
sx = sx+x;
}
System.out.println(sx);
}
}
Example:
public static void main(String[] args) {
String s = "1234ajhdhols233adfjal";
String str = s.replaceAll("\\d", "");
System.out.println(str);
}

Categories