Write a java program to Count String Occurrences.

Obtain two strings from the user as input. Your program should count the number of occurrences of the second word of the second sentence in the first sentence as a output you need to find count string occurrences in a string.

Return the count as output. Note – Consider case.

The return type is the modified string.

Input and Output Format:

Input consists of two strings with the maximum size of 100 characters.

The output consists of a single string.

Refer sample output for formatting specifications.

Sample Input 1:

abc bcd abc bcd abc abc

av abc

Sample Output 1:

4

Sample Input 2:

ABC xyz AAA

w abc

Sample Output 2:

0

Count String Occurrences in Java.

 import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
  Scanner sc= new Scanner(System.in);
String s1=sc.nextLine();
String s2=sc.nextLine();
getvalues(s1,s2);
}
public static void getvalues(String s1, String s2) {
int count=0;
StringTokenizer st=new StringTokenizer(s2," ");
String s3=st.nextToken();
String s4=st.nextToken();
//System.out.println(s4);
StringTokenizer st1=new StringTokenizer(s1," ");
while(st1.hasMoreTokens())
{
String s5=st1.nextToken();
if(s4.equals(s5))
{
count++;
}
}
System.out.println(count);
}
}



Write a java program to find the longest word from a string.

Write a Program which finds the longest word from a sentence. Your program should read a sentence as input from the user and return the longest word.In case there are two words of maximum length return the word which comes first in the sentence.

Input and Output Format:

Input consists of a string with maximum size of 100 characters.

Output consists of a single string.

Refer sample output for formatting specifications.

Sample Input 1:

Welcome to the world of Programming

Sample Output 1:

Programming

Sample Input 2:

ABC DEF

Sample Output 2:

ABC

Find the longest word from a string in Java.

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s1 = sc.nextLine();
    System.out.println(lengthiestString(s1));
  }

  public static String lengthiestString(String s1) {
    int max = 0;
    String s2 = new String();
    StringTokenizer t = new StringTokenizer(s1, " ");
    loop: while (t.hasMoreTokens()) {
      String s3 = t.nextToken();
      int n = s3.length();
      if (n > max) {
        max = n;
        s2 = s3;
      }
    }
    return s2;
  }
}

 

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *

six + 15 =