Sei sulla pagina 1di 20

1) How to Print duplicate characters from String?

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
/**
* Java Program to find duplicate characters in String.
*
*
* @author http://java67.blogspot.com
*/
public class FindDuplicateCharacters{
public static void main(String args[]) {
printDuplicateCharacters("Programming");
printDuplicateCharacters("Combination");
printDuplicateCharacters("Java");
}
/*
* Find all duplicate characters in a String and print each of them.
*/
public static void printDuplicateCharacters(String word) {
char[] characters = word.toCharArray();
// build HashMap with character and number of times they appear in String

Map<Character, Integer> charMap = new HashMap<Character, Integer>();


for (Character ch : characters) {
if (charMap.containsKey(ch)) {
charMap.put(ch, charMap.get(ch) + 1);
} else {
charMap.put(ch, 1);
}
}
// Iterate through HashMap to print all duplicate characters of String
Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet();
System.out.printf("List of duplicate characters in String '%s' %n", word);
for (Map.Entry<Character, Integer> entry : entrySet) {
if (entry.getValue() > 1) {
System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());
}
}
}
}
Output
List of duplicate characters in String 'Programming'
g:2
r:2
m:2

List of duplicate characters in String 'Combination'


n:2
o:2
i:2
List of duplicate characters in String 'Java'
(OR)
import java.util.*;
import java.io.*;

class Ideone
{
public static void main (String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String s = br.readLine();
int len = s.length();

int[] charCount = new int[26];

for(int i = 0; i=65 && c<=90)


c=(char)(c+32);
if(c>=97 && c<=122)

charCount[c-97]+=1;
}

for(int i = 0; i<26; i++){


if(charCount[i]>1)
System.out.println((char)(i+97) + " : " + charCount[i]);
}
}
}
2) How to check if two Strings are anagrams of each other?
import java.util.Arrays;
public class AnagramCheck {

/*
* One way to find if two Strings are anagram in Java. This method
* assumes both arguments are not null and in lowercase.
*
* @return true, if both String are anagram
*/
public static boolean isAnagram(String word, String anagram){
if(word.length() != anagram.length()){
return false;
}

char[] chars = word.toCharArray();

for(char c : chars){
int index = anagram.indexOf(c);
if(index != -1){
anagram = anagram.substring(0,index) +
anagram.substring(index +1, anagram.length());
}else{
return false;
}
}

return anagram.isEmpty();
}

/*
* Another way to check if two Strings are anagram or not in Java
* This method assumes that both word and anagram are not null and lowercase
* @return true, if both Strings are anagram.
*/
public static boolean iAnagram(String word, String anagram){
char[] charFromWord = word.toCharArray();
char[] charFromAnagram = anagram.toCharArray();
Arrays.sort(charFromWord);
Arrays.sort(charFromAnagram);

return Arrays.equals(charFromWord, charFromAnagram);


}

public static boolean checkAnagram(String first, String second){


char[] characters = first.toCharArray();
StringBuilder sbSecond = new StringBuilder(second);

for(char ch : characters){
int index = sbSecond.indexOf("" + ch);
if(index != -1){
sbSecond.deleteCharAt(index);
}else{
return false;
}
}

return sbSecond.length()==0 ? true : false;


}
}

4) How to reverse String in Java using Iteration and Recursion? (without using
StringBuffer class)
import java.io.FileNotFoundException;
import java.io.IOException;

public class StringReverseExample {


public static void main(String args[]) throws FileNotFoundException, IOException
{
//original string
String str = "Sony is going to introduce Internet TV soon";
System.out.println("Original String: " + str);
//reversed string using Stringbuffer
String reverseStr = new StringBuffer(str).reverse().toString();
System.out.println("Reverse String in Java using StringBuffer: " + reverseStr);
//iterative method to reverse String in Java
reverseStr = reverse(str);
System.out.println("Reverse String in Java using Iteration: " + reverseStr);
//recursive method to reverse String in Java
reverseStr = reverseRecursively(str);
System.out.println("Reverse String in Java using Recursion: " + reverseStr);
}
public static String reverse(String str) {
StringBuilder strBuilder = new StringBuilder();
char[] strChars = str.toCharArray();
for (int i = strChars.length - 1; i >= 0; i--) {
strBuilder.append(strChars[i]);
}
return strBuilder.toString();
}

public static String reverseRecursively(String str) {


//base case to handle one char string and empty string
if (str.length() < 2) {
return str;
}
return reverseRecursively(str.substring(1)) + str.charAt(0);
}
}
5) How to count number of vowels and consonants in a String?
import java.util.Scanner;
/**
* Java Program to count vowels in a String. It accept a String from command
prompt
* and count how many vowels it contains. To revise, 5 letters a, e, i, o and u are
* known as vowels in English.
*/
public class VowelCounter {
public static void main(String args[]) {
System.out.println("Please enter some text");
Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
char[] letters = input.toCharArray();
int count = 0;

for (char c : letters) {


switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
break;
default:
// no count increment
}
}
System.out.println("Number of vowels in String [" + input + "] is : " + count);
}
}
Output:
Please enter some text
How many vowels in this String
Number of vowels in String [How many vowels in this String] is : 7
6) How to convert numeric String to an int?
//using Integer.parseInt
int i = Integer.parseInt("123");

System.out.println("i: " + i);


(OR)
This is a new way of converting an int primitive to String object and introduced in
JDK 1.5 along-with several other important features like Enum, Generics and
Variable argument methods. String.format() is even more powerful and can be used
in variety of way to format String in Java.
String price = String.format ("%d", 123);
7) How to reverse words in a sentence without using library method?
public class ReverseString {
public static void main(String[] args) {
String str="Hello world";
String revstring="";
for(int i=str.length()-1;i>=0;--i){
revstring +=str.charAt(i);
}
System.out.println(revstring);
}
}
8) How to check if String is Palindrome?
private static void palindrome(String string) {
char[] ch = string.toCharArray();
int count =0;
for(int i=0; i< ch.length/2; i++) {
if(ch[i] == ch[ ch.length-1-i]){

count++;
continue;

}else{
count =0;
System.out.println("not palindrome");
}
}

if(count >0) {
System.out.println(" palindrome");
}

}
(OR)
public class PalindromeDemo{
public static void main(String[] args) {
String str="MADAM";
String revstring="";
for(int i=str.length()-1;i>=0;--i){
revstring +=str.charAt(i);
}
System.out.println(revstring);

if(revstring.equalsIgnoreCase(str)){
System.out.println("The string is Palindrome");
}
else{
System.out.println("Not Palindrome");
}
}
}
9) Sorting the String without using String API?
public class SortString {
public static void main(String[] args) {
String original = "edcba";
int j=0;
char temp=0;
char[] chars = original.toCharArray();
for (int i = 0; i <chars.length; i++) {
for ( j = 0; j < chars.length; j++) {
if(chars[j]>chars[i]){
temp=chars[i];
chars[i]=chars[j];
chars[j]=temp;
}
}

}
for(int k=0;k<chars.length;k++){
System.out.println(chars[k]);
}
}
}
10) Sort the String with using String API?
public class SortString {
public static void main(String[] args) {
String original = "edcba";
char[] chars = original.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
System.out.println(sorted);
}
}
11) Program to Check given number is palindrome or not?
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args)
{
System.out.println("Please Enter a number : ");
int givennumber = new Scanner(System.in).nextInt();

int number=givennumber;
int reverse=0;
while (number != 0) {
int remainder = number % 10;
reverse = reverse * 10 + remainder;
number = number / 10;
}
if(givennumber == reverse)
System.out.println("Result:Palindrome");
else
System.out.println("Result:Not Palindrome");
}

}
Output:
Please Enter a number :
535
Result:Palindrome
12) Java Program to count number of vowels in a string
public class CountNumberofVowels {
public static void main(String[] args) {
System.out.println("Please enter a String");
Scanner in = new Scanner(System.in);

String input = in.nextLine();


char[] Chararray = input.toCharArray();
int count = 0;
for (char ch : Chararray) {
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
count++;
break;
default:
}
}
System.out.println("Number of vowels in String "+count);
}
}

(OR)
public class CountNumberofVowels {
public static void main(String[] args) {
int vowels = 0, digits = 0, blanks = 0; char ch;
System.out.println("Please enter a String");
Scanner in = new Scanner(System.in);
String testString= in.nextLine();
for (int i = 0; i < testString.length(); i ++)
{
ch = testString.charAt(i);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowels ++;
else if(Character.isDigit(ch))
digits ++;
else if(Character.isWhitespace(ch))
blanks ++;
}
System.out.println("Vowels : " + vowels);
System.out.println("Digits : " + digits);
System.out.println("Blanks : " + blanks);
}
}

--

2) Write a java program to remove all white spaces from a string.?


A): 1) Using replaceAll() Method.

In the first method, we use replaceAll() method of String class to remove all white
spaces (including tab also) from a string. This is the one of the easiest method to
remove all white spaces from a string. This method takes two parameters. One is
the string to be replaced and another one is the string to be replaced with. We pass
the string \s to be replaced with an empty string .

2) Without Using replaceAll() Method.

In the second method, we remove all white spaces (including tab also) from a string
without using replaceAll() method. First we convert the given string to char array
and then we traverse this array to find white spaces. We append the characters
which are not the white spaces to StringBuffer object.

Here is the java program which uses both the methods to remove white spaces from
a string.
class RemoveWhiteSpaces
{
public static void main(String[] args)
{
String str = " Core Java jsp servlets

jdbc struts hibernate spring ";

//1. Using replaceAll() Method


String strWithoutSpace = str.replaceAll("\\s", "");
System.out.println(strWithoutSpace);
CoreJavajspservletsjdbcstrutshibernatespring
//2. Without Using replaceAll() Method
char[] strArray = str.toCharArray();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < strArray.length; i++)

//Output :

{
if( (strArray[i] != ' ') && (strArray[i] != '\t') )
{
sb.append(strArray[i]);
}
}
System.out.println(sb);
//Output :
CoreJavajspservletsjdbcstrutshibernatespring
}
}
3) Armstrong number program in java
A): public class MainClass
{
static void checkArmstrongNumber(int number)
{
int copyOfNumber = number;
int noOfDigits = String.valueOf(number).length();
int sum = 0;
while (copyOfNumber != 0)
{
int lastDigit = copyOfNumber % 10;
int lastDigitToThePowerOfNoOfDigits = 1;
for(int i = 0; i < noOfDigits; i++)
{
lastDigitToThePowerOfNoOfDigits =
lastDigitToThePowerOfNoOfDigits * lastDigit;
}
sum = sum + lastDigitToThePowerOfNoOfDigits;
copyOfNumber = copyOfNumber / 10;
}

if (sum == number)
{
System.out.println(number+" is an armstrong number");
}
else
{
System.out.println(number+" is not an armstrong number");
}
}
public static void main(String[] args)
{
checkArmstrongNumber(153);
checkArmstrongNumber(371);
checkArmstrongNumber(9474);
checkArmstrongNumber(54748);
checkArmstrongNumber(407);
checkArmstrongNumber(1674);
}
}

Output :
153 is an armstrong number
371 is an armstrong number
9474 is an armstrong number
54748 is an armstrong number
407 is an armstrong number
1674 is not an armstrong number
5) How to check whether user input is number or not in java?
boolean numberOrNot(String input)
{
try
{
Integer.parseInt(input);
}

catch(NumberFormatException ex)
{
return false;
}
return true;

-class Utility
{
static boolean numberOrNot(String input)
{
try
{
Integer.parseInt(input);
}
catch(NumberFormatException ex)
{
return false;
}
return true;
}
}
public class CheckMobileNumber
{
public static void main(String[] args)
{
System.out.println("Enter your mobile number");
Scanner sc = new Scanner(System.in);
String input = sc.next();
if(Utility.numberOrNot(input) && (input.length() == 10))
{
System.out.println("Good!!! You have entered valid mobile
number");
}
else
{
System.out.println("Sorry!!!! You have entered invalid
mobile number. Try again...");
}
}
}

Potrebbero piacerti anche