Showing posts with label character. Show all posts
Showing posts with label character. Show all posts

Java: How to test if two Strings (words) are anagram using a Character Array?

Question:
How to test if two words are anagram using Arrays.sort()?

Code:
import java.util.Scanner;
 
public class Anagram {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter first word: ");
    String word1 = sc.nextLine();
    System.out.print("Enter second word: ");
    String word2 = sc.nextLine();
 
    System.out.println("Anagram: " + isAnagram(word1,word2));
 
   }
 
 
  // Test if two words are Anagram using Character Array
  public static boolean isAnagram(String word1, String word2) {
 
    word1 = word1.toLowerCase();
    word2 = word2.toLowerCase();
 
    if (word1.length() != word2.length()) {
      return false;
    }
 
    char[] chars = word1.toCharArray();
    for (char c : chars) {
      int index = word2.indexOf(c);
      if (index != -1) {
        word2 = word2.substring(0, index) + word2.substring(index + 1, word2.length());
      } else {
        return false;
      }
    }
    return word2.isEmpty();
  }
}

Output:
$ java Anagram
Enter first word: Star
Enter second word: rats
Anagram: true

$ java Anagram
Enter first word: rate
Enter second word: tree
Anagram: false

How to convert ASCII code to char in Java?

Question:
How to convert ASCII code to char in Java?

Answer:
Simply casting int to char

Code:
public class ConvertASCIItoChar {
  public static void main(String[] args) {
    for(int i=32;i<=126;i++){
      char c = (char)i;
        System.out.print(c);
    }
    System.out.println();
  }
} 

Output:
$ java ConvertASCIItoChar
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

How can you test if a character is between 'a' and 'z'?

Question:
How can you validate that a scanner input is a character between 'a' and 'z'?

Code:
import java.util.Scanner;
public class ReadChar {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner( System.in );
 
    String str = "";
    while(true) {
      System.out.print("Please enter a letter: ");
      str = sc.nextLine();
      if(str.length() == 1) {
        char c = str.charAt(0);
        if( (c >= 'a') && (c <= 'z')) {
          break;
        }
      }
      System.out.println("Try again.");
    }
    System.out.println("You entered: " + str);
 
  }
}

Output:
$ java ReadChar
Please enter a letter: A
Try again.
Please enter a letter: s
You entered: s

How to remove all occurrences of a letter from a string?

Question:
How to remove all occurrences of a letter from a string?

Answer:
Use a for loop and compare each character of the string to see if it matches the letter that needs to be removed. Build a new string based on the results.

Use the String.replace() method.

Code:
public class RemoveChars {
   public static void main(String[] args) {
 
      String str1 = "axbxcxdxex";
      String str2 = "";
      String str3 = "";
 
      // using a for loop 
      for (int i = 0; i < str1.length(); i++) {
         if (str1.charAt(i) != 'x') {
            str2 = str2 + str1.charAt(i);
         }
      }
 
      // using a for String.replace()
      str3 = str1.replace( "x", "");
 
      System.out.println(str1);
      System.out.println(str2);
      System.out.println(str3);
  }
}

Output:
$ java RemoveChars 
axbxcxdxex
abcde
abcde

Getting the first char of each line in a file.

Question:
How can I get the first character of each line in a file?

Answer:
See code.

Code:
import java.io.*;
 
public class ReadFile {
   public static void main(String[] args) {
      try {
         FileInputStream is = new FileInputStream("file.txt");
         BufferedReader br = new BufferedReader(new InputStreamReader(is));
         String str;
         while ((str = br.readLine()) != null)   {
 
            char first = str.charAt(0);
            System.out.println(first);
 
         }
      } catch (Exception e) {
      }
   }
}

Output:
$ java ReadFile 
a
b
c
d

$ cat file.txt 
a bbb ccc ddd
bb ccc dddd eeee
cccc dd ee f
dd eeeeee fff ggg

Write each character of a string to a queue (FIFO) and then read it back one character at a time.

Question:
Write each character of a string to a queue (FIFO) and then read it back one character at a time.

Answer:
Here is an example using the LinkedList class which implements a Queue. The string is put into the queue one letter at a time. Then read back one letter at a time.

Code:
import java.util.*;
 
public class QueueExample {
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter string: ");
      String str = sc.nextLine();
 
      Queue<Character> queue = new LinkedList<Character>();
 
      for(int i=0; i<str.length(); i++){
         queue.add(str.charAt(i));
      }
 
      String str2 = "";
      while( queue.peek() != null ){
        str2 = str2 + queue.remove(); 
        System.out.println(str2); 
      }
   }
}

Output:
$ java QueueExample
Enter string: ABCDEFGHIJ
A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
ABCDEFGHIJ

Remove a character from a particular position in a string.

Question:
How can you remove a character from a particular position in a string?

Answer:
Create 2 sub strings. The first one will be everything before the char to be removed. The second one will be everything after the char is removed. Then concatenate the two sub strings together.

Code:
public class RemoveCharacter {
 
   public static void main(String args[]) {
 
      String str1 = "This is java";
 
      // position to remove
      int pos = 8;
 
      String str2 = str1.substring(0, pos) + str1.substring(pos + 1);
 
      System.out.println("Original String: " + str1);
      System.out.println("New String:      " + str2);
   }
}

Output:
$ java RemoveCharacter 
Original String: This is java
New String:      This is ava