Drop Down

Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

Wednesday, February 6, 2019

Program to Reverse an array

Solution 1 - Revere array in Place (not recommended)



package interview;

import java.util.Arrays;
import java.util.List;

public class Reverse_Array {

public static void main(String[] args)
{
   int[] arr = {1,2,3,4,5,6,7,8,9,10};
   System.out.println("Before : "+Arrays.toString(arr));
   /*List<int[]> l = Arrays.asList(arr);
   System.out.println(l.toArray());*/
   for(int i =0 , j = arr.length-1; i<j; i++,j--)
   {
   int temp = arr[i];
   arr[i] = arr[j];
   arr[j] = temp;
 
   }
   System.out.println("After : "+Arrays.toString(arr));
 
 
}

}

Solution 2 - Revere array in Place (for interview)


package phase_one;

import java.util.Arrays;

public class ReverseArray_Using_ForLoop 
{
public static void main(String[] args) 
{
  int[] arr = new int[] {7,84,3,9,11,6};
  System.out.println("Before: "+Arrays.toString(arr));
  for(int i= 0;i<arr.length/2;i++)
  {
  int temp = arr[i];
  arr[i] =   arr[arr.length-i-1];
  arr[arr.length-i-1] = temp;
  }
  System.out.println("After: "+Arrays.toString(arr));
}

}

Solution 3 - Revere array Using Collections


package phase_one;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ReverseArray_Using_ArrayList {

public static void main(String[] args) 
{
String[] arr = {"apple", "tree", "play"};
      System.out.println("before: " + Arrays.toString(arr) );
      List<String> listOfProducts = Arrays.asList(arr);      
      Collections.reverse(listOfProducts);
      String[] reversed = listOfProducts.toArray(arr);
      System.out.println("after: " + Arrays.toString(reversed) );
      
      System.out.println("**************************************");
     
      Integer[] arr2 = new Integer[] {1,2,3,4,5};
     // List<Integer> list = Arrays.asList(arr2);       
     System.out.println(Arrays.toString(arr2));
     List<Integer> li = Arrays.asList(arr2);  //--array to List
     Collections.reverse(li); // reverse List
     Integer[] rev = li.toArray(arr2);
     System.out.println(Arrays.toString(rev));
     
 

}

}

Reverse_String_Without_API

package interview;

public class Reverse_String_Without_API {

public static void main(String[] args)
{
String str = "Gopalpur";
String reverse = "";
char[] ch = str.toCharArray();
for(int i = ch.length-1; i>=0;i--)
{
reverse = reverse +ch[i];
}
System.out.println(reverse);
}

}


Swapping_Two_Numbers_without_Temp_Variable

package interview;

public class Swapping_Two_Numbers_without_Temp_Variable
{

public static void main(String[] args)
{
  int num1 = 54;
  int num2 = 45;
  num1 = num1 + num2;
  num2 = num1 - num2;
  num1 = num1 - num2;
  System.out.println("num1: "+num1);
  System.out.println("num2: "+num2);

}

}

RemoveWhiteSpace_PrintNoLasComma

public class RemoveWhiteSpace_PrintNoLasComma{

public static void main(String[] args)
{
   String str = "Hello wor   ld";
   str = str.replaceAll("\\s","");
   //System.out.println(str);
   char[] ch = str.toCharArray();
   for(int i =0;i<ch.length;i++)
   { 
   System.out.print((i == 0 ? ch[i] :","+ch[i] ));
   }

}

}

Tuesday, February 5, 2019

DuplicateStrings

package interview;
import java.util.*;
public class DuplicateStrings
{
//String-->String.split()--->String[]--->Uppercase--->Hashmap
public static void main(String[] args)
{
  String str = "This is what is this world in world 45 67 45";
  String[] str2 = str.split(" ");
  String[] str3 = toUpperString(str2);
  show(str3);

  Map<String,Integer> map = new HashMap<>();
  for(String s : str3)
  {
  if(map.containsKey(s))
  {
  map.put(s,map.get(s)+1);
  }
  else
  {
  map.put(s, 1);
  }
  }
//*****************************
  for(Map.Entry<String,Integer> entry : map.entrySet())
  {
  if(entry.getValue()>1)
  {
  System.out.println(entry.getKey()+" --->"+entry.getValue());
  }
  }

}

    private static void show(String[] str3)
    {
  for(String s : str3)
  System.out.print(s+" ");
  System.out.println("");
    }

private static String[] toUpperString(String[] str2)
     {
for(int i =0;i<str2.length;i++)
{
str2[i] = str2[i].toUpperCase();
}
    return str2;
     }

}

Permutation

package interview;

public class Permuter
{
public static void main(String[] args)
{
String str = "ABC";
permute(str,0,str.length()-1);
}

private static void permute(String str, int start, int end)
{
if(start==end)
{
System.out.println(str);
return;
}
   for(int i = start;i<=end;i++)
   {
   str = swap(str,start,i);
   permute(str,start+1,end);
   str = swap(str,start,i);  
 
   }

}

private static String swap(String str, int start, int i)
{
    char[] ch = str.toCharArray();
    char temp = ch[start];
    ch[start]= ch[i];
    ch[i] = temp;
    //String str2 = ch.toString();    
return String.valueOf(ch);
}
}

Program to count vowels, consonant, digits and special characters in string

package test;

import java.util.Scanner;

public class Count_vowel_cons_digit_symbol
{

public static void main(String[] args)
{
  System.out.println("Enter string");
  Scanner kb = new Scanner(System.in);
  String string = kb.nextLine();
  displaycount(string);
}

private static void displaycount(String s)
{
int vowel =0;
int consonent =0;
int whitespace = 0;
int digit = 0;
int symbol = 0;
String string = s.toLowerCase();
System.out.println(string);
   for(int i=0;i<string.length();i++)
   {
   char ch = string.charAt(i);
 
   if((ch>='a' && ch<='z')||(ch>='A' && ch<='Z'))
   {
   switch(ch)
   {
   case 'a':
   case 'e':
   case 'i':
   case 'o':
   case 'u':  
   vowel++;
   break;
   default:
   consonent++;
   }  
 
   }
   else if(ch>='0' && ch<='9')
        digit++;
   else if(Character.isWhitespace(ch))
        whitespace++;
   else
   {
   symbol++;
   }
   }
 
   System.out.println("Vowels: "+vowel);
   System.out.println("consonent: "+consonent);
   System.out.println("whitespace: "+whitespace);
   System.out.println("digit: "+digit);
   System.out.println("symbol: "+symbol);

}

}

Monday, February 4, 2019

Count Words,char,duplicate Words from File

package test;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/*
No. of Words:
No. of characters:
List to duplicate Words:
D:\work\Java Work Space\files\amit.txt
*/
public class Count_Duplicate_Words_From_File
{
public static void main(String[] args) throws IOException, FileNotFoundException
{
  BufferedReader br = new BufferedReader(new FileReader("D:\\work\\Java Work Space\\files\\amit.txt"));
  StringBuffer sb = new StringBuffer();
  String s = br.readLine();
  while(s!= null)
  {
  //sb = sb.append(s); //----->White ko hatna hetu
  sb = sb.append(s.trim());
  sb = sb.append(" ");
  s = br.readLine();
  }
  br.close();
  String[] words = sb.toString().split(" ");
  wordCount(words);
  charCount(words);
  DupWords(words);
 
}

private static void DupWords(String[] words)
{
  Map <String,Integer> map = new HashMap<>();
  for(String s : words)
  {
  if(!map.containsKey(s))
  {
  map.put(s, 1);
  }
  else
  {
  map.put(s, map.get(s)+1);
  }
  }
  System.out.println("List to duplicate Words:");
  for(Map.Entry<String,Integer> entry : map.entrySet())
  {
  if(entry.getValue()>1)
  System.out.println(entry.getKey()+" : "+entry.getValue());
  }

}

private static void charCount(String[] words)
{
char[] ch;
int count = -1;
  for (String s : words)
  {
for(int i = 0;i<s.length();i++)
{
count++;
}
count++;
  }
  System.out.println("No. of characters: "+count);

}

private static void wordCount(String[] words)
{
  System.out.println(Arrays.toString(words));
  System.out.println("No of Words: "+words.length);

}
}

AnagramString

package interview;
import java.util.*;

public class AnagramString {

public static void main(String[] args)
{
  String s1 ="mang o";
  String s2 ="Nam go";
  System.out.println(s1+" & "+s2);
  checkAnagram(s1,s2);
 
}

private static void checkAnagram(String s1, String s2)
{
/*
  * remove white space
  * remove case
  * check for count
*/
String a = s1.replace(" ", "").toLowerCase();
String b = s2.replace(" ", "").toLowerCase();

char[] ch1 = a.toCharArray();
char[] ch2 = b.toCharArray();
Arrays.sort(ch1);
Arrays.sort(ch2);
if(Arrays.equals(ch1,ch2))
{
System.out.println("Yes It is Anagram");
}
else
System.out.println("Not Anagram");

}

}

AnagramString2

package interview;

public class AnagramString2 {

public static void main(String[] args)
{
String s1 ="java";
String s2 ="avaj";
StringBuffer sb = new StringBuffer(s2);
char[] ch = s1.toCharArray();
for (char c : ch)
{
//int index = sb.indexOf(String.valueOf(c)); --or
int index = sb.indexOf(Character.toString(c));
sb.deleteCharAt(index);
}
System.out.println(sb.length()==0?"Anagram":"Not Anagram");

}

}

Check_If_String_Contains_only_Digit

package interview;

public class Check_If_String_Contains_only_Digit {

public static void main(String[] args)
{
  String str = "Error 404 detected in server 589.90 ";
  char[] ch = str.toCharArray();
  System.out.println(ch);
  String str2 = str.replaceAll("[^0-9]","");
  System.out.println(str2);
}

}

Count_Character_WithoutLoop

package interview;
//Write a program to find the number of occurrences of a given character in a string without using loop
public class Count_Character_WithoutLoop {

public static void main(String[] args)
{
  String str = "This is an apple";
      System.out.println("Length Of String:" + str.length());
      System.out.println("Length Of String Without a :" + str.replace("a", "").length());
      //System.out.println(">>>"+str.replace("a", ""));
      int charcount = str.length() - str.replaceAll("a", "").length();
      System.out.println("Occurrence Of A Char In String: " + charcount);

}

}




     

Count Words

package interview;

public class CountWords {

public static void main(String[] args)
{
   String s1 = "All izz well";
   String[] str = s1.split(" ");
   System.out.println(str.length);
 
 
   /*String str2 = "This is what is this world in world 45 67 45";
   int l = str2.split(" ").length;
   System.out.println("len: "+l);*/
 
   /*String s1 = "All~izz~well";
   int l = s1.split("~").length;
   System.out.println(">>"+l);*/
   String[] str2 = {"abc","def","ghi"};
   for (String string : str)
   {
System.out.print(string+" ");
   }

}

}

Duplicate Char

package interview;
//count no. of duplicate character occurance
import java.util.*;
//steps:
//string --->char array---->(convert to lowercase)---->hashmap
public class DuplicateChar {

public static void main(String[] args)
{
  String str  ="programming world445";
  char[] ch = str.toCharArray();
  char[] upper_ch = convertLower(ch);
  System.out.println(upper_ch);
 
  Map<Character, Integer> map = new HashMap<>();
  for(char c : upper_ch)
  {
  if(map.containsKey(c))
  {
  map.put(c, map.get(c)+1);
  }
  else
  {
  map.put(c, 1);
  }
  }
 
  //****************
  for(Map.Entry<Character,Integer>entry : map.entrySet())
  {
  if(entry.getValue()>1)
  {
  System.out.println(entry.getKey()+"-->"+entry.getValue());
  }
  }
 
 
}
//***********************************
private static char[] convertLower(char[] ch)
{
  for(int i=0;i<ch.length;i++)
  {
  if(Character.isLetter(ch[i])&& (Character.isLowerCase(ch[i])))
    {
  ch[i]= Character.toUpperCase(ch[i]); 
}
  }
return ch;
}


}

Duplic_Char

package interview;

public class Duplic_Char {

public static void main(String[] args)
{
String str = "abcd defg abd ghi";
  //int cnt = 0;
  char[] inp = str.toCharArray();
  System.out.println("Duplicate Characters are:");
  for (int i = 0; i < str.length(); i++)
  {
  for (int j = i + 1; j < str.length(); j++)
  {
  if (inp[i] == inp[j])
  {
  System.out.println(inp[j]);
  //cnt++;
               break;
             }
       }
   }

}}

Duplicate Char Display

package interview;

import java.util.*;

public class DuplicateCharDisplay {

public static void main(String[] args)
{
  String str = "welcome to apple world";
  displayDuplicate(str);

}

private static void displayDuplicate(String str)
{
  Map <Character,Integer> map = new HashMap<>();
  char  [] ch = str.toCharArray();
  for(char c : ch)
  {
  if(!map.containsKey(c))
  {
  map.put(c, 1);
  }
  else
  {
map.put(c, map.get(c)+1); 
  }
  }
  // Now Iterate map
  /*for(char c : map.keySet())
  {
  System.out.println(c +" - "+map.get(c));
  }*/
 
  for(Map.Entry<Character,Integer> entry : map.entrySet())
{
    if(entry.getValue()>1)
    {
System.out.printf("%s : %d %n",entry.getKey(),entry.getValue());
    }
}
}

}

Duplicate Strings

package interview;
import java.util.*;
public class DuplicateStrings
{
//String-->String.split()--->String[]--->Uppercase--->Hashmap
public static void main(String[] args)
{
  String str = "This is what is this world in world 45 67 45";
  String[] str2 = str.split(" ");
  String[] str3 = toUpperString(str2);
  show(str3);
 
  Map<String,Integer> map = new HashMap<>();
  for(String s : str3)
  {
  if(map.containsKey(s))
  {
  map.put(s,map.get(s)+1);
  }
  else
  {
  map.put(s, 1);
  }
  }
//*****************************
  for(Map.Entry<String,Integer> entry : map.entrySet())
  {
  if(entry.getValue()>1)
  {
  System.out.println(entry.getKey()+" --->"+entry.getValue());
  }
  }
 
}

    private static void show(String[] str3)
    {
  for(String s : str3)
  System.out.print(s+" ");
  System.out.println("");
    }

private static String[] toUpperString(String[] str2)
     {
for(int i =0;i<str2.length;i++)
{
str2[i] = str2[i].toUpperCase();
}
    return str2;
     }

}

Fibonacci

package interview;

public class Fibonacci {

public static void main(String[] args)
{
  int fib1 = 0;
  int fib2 = 1;  
  int fib3;
  int limit = 10;
  System.out.println("First "+limit+" terms");
  for(int i = 1; i<limit;++i)
  {
  System.out.println(fib1);
  fib3 = fib1+ fib2;
  fib1 = fib2;
  fib2 = fib3;
  }

}

}

First Non Repeated Character

package interview;

import java.util.*;

//Print first Non Repeated character
public class FirstNonRepeatedCharacter {

public static void main(String[] args)
{
  String str = "computercomputes";
  char[] ch = str.toCharArray();
  LinkedHashMap<Character,Integer> link = new LinkedHashMap<>();
  for(int i = 0;i<ch.length;i++)
  {
  if(link.containsKey(ch[i]))
  {
  link.put(ch[i], link.get(ch[i])+1);
  }
  else
  {
  link.put(ch[i],1);
  }
  }
  //***Iterate
  for(Map.Entry<Character,Integer> entry : link.entrySet())
  {
  if(entry.getValue()==1)
  {
  System.out.println("first NRC: "+entry.getKey());
  System.out.println("first NRC: "+entry.getKey().toString().toUpperCase());
  return;
  }
  }
 
 

}

}

Palindrom_Num

package interview;

public class Palindrom_Num {
//reverse karke check kar lo
public static void main(String[] args)
{
  int a = 121;
  int t = a;
  int rev=0;
  int temp = 0;
  while(a>0)
  {
  temp = a%10;
  rev = (rev*10)+temp;
  a= a/10;  
  }
  if(t == rev)
  System.out.println("Palindrom");
  else
  System.out.println("Not Palindrom");
 
 
//Method 2: Starts ***********************************************
int num2 = 1210121;  
   StringBuffer sb7 = new StringBuffer(num2);
   if(sb7==sb7.reverse())
   System.out.println(num2+" : is Pelindrom");
   else
   System.out.println(num2+" : is Not Pelindrom");
 //Method 2 :Ends ***********************************************
}



}

Java 8 Notes Pics