Skip to main content

Posts

Showing posts with the label String

Program to find the frequency of characters in given string in java

Program to find the frequency of characters in given string in java  For Explanation Watch Video : Code:: import java.util.*; import java.io.*; import java.lang.*; class Test{ public static void main(String[] args) { String name = "idiot"; Map<Character,Integer> map = new HashMap<Character,Integer>(); for(int i=0;i<name.length();i++){ Character ch = name.charAt(i); map.put(ch,map.getOrDefault(ch,0)+1); } System.out.println(map); for(Map.Entry<Character,Integer> e : map.entrySet()){ System.out.println(e.getKey()+" "+e.getValue()); } } } o/p: {d=1, t=1, i=2, o=1} d 1 t 1 i 2 o 1

remove duplicate words from string in java

 remove duplicate words from string in java For Explanation Watch Video:  Program:: import java.util.*; class College { public static void main(String[] args){ String sen = " Sam went went to to to his business "; String[] arr = sen.split(" "); //arr={Sam,went,went,to,to ,to ,his ,business}; Set<String> s = new LinkedHashSet<String>(); for(int i=0;i<arr.length;i++){ s.add(arr[i]); } for(String ss:s){ System.out.print(ss+" "); } System.out.println(); } } o/p:  Sam went to his business Using Java 8 import java.util.*; class College { public static void main(String[] args){ String sen = "Sam went went to to to his business"; sen = Arrays.stream(sen.split(" ")).distinct().collect(Collectors.joining(" "); } }

Reverse a string using Stack in java

 Reverse a string using Stack in java Explanation Of code: Code: import java.util.Stack; class Test{ public static void main(String[] args){ String s = "Baburao"; System.out.println(reverse(s));     } public static String reverse(String s){ Stack<Character> st = new Stack<>(); String reverse = ""; for(int i=0;i<s.length();i++){ st.push(s.charAt(i)); } while(st.size()!=0){ reverse = reverse + st.pop(); } return reverse; } } o/p:oarubaB