w3resource

Java String Exercises: Print list items containing all characters of a specified word

Java String: Exercise-42 with Solution

Write a Java program to print list items containing all characters of a given word.

Pictorial Presentation:

Java String Exercises: Print list items containing all characters of a specified word

Sample Solution:

Java Code:

import java.util.*;
class Main {
 static void checkExistance(String str1, String str_to_search) {
  int chk = 0;
  char chhr = ' ';
  int[] a = new int[Character.MAX_VALUE + 1];

  for (int i = 0; i < str1.length(); i++) {
   chhr = str1.charAt(i);
   ++a[chhr];
  }
  for (int i = 0; i < str_to_search.length(); i++) {
   chhr = str_to_search.charAt(i);
   if (a[chhr] >= 1)
    chk = 1;
  }
  if (chk == 1)
   System.out.println(str1);
 }

 public static void main(String[] args) {
  List < String > list = new ArrayList < String > ();
  list.add("rabbit");
  list.add("bribe");
  list.add("dog");
  System.out.print("The given strings are: ");
  for (int i = 0; i < list.size(); i++) {
   System.out.print(list.get(i) + "   ");
  }
  System.out.println("\nThe given word is: bib ");
  System.out.println("\nThe strings containing all the letters of the given word are: ");
  for (int j = 0; j < list.size(); j++) {
   checkExistance(list.get(j), "bib");
  }
 }
}

Sample Output:

The given strings are: rabbit   bribe   dog   
The given word is: bib 

The strings containing all the letters of the given word are: 
rabbit
bribe

Flowchart:

Flowchart: Java String Exercises - Print list items containing all characters of a specified word

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to remove duplicate characters from a given string presents in another given string.
Next: Write a Java program to find the maximum occurring character in a string.

What is the difficulty level of this exercise?



Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH