String Interview Programs
String Interview Programs
String Interview Programs
------------------------------
class reverseWithoutAPI
{
public static void main(String a[])
{
String str="Java 2 career";
String arr[]=str.split(" ");
System.out.print("Reversed String of "+str+":");
for(int i=arr.length-1;i>=0;i--)
{
char temp[]=arr[i].toCharArray();
for(int j=temp.length-1;j>=0;j--)
{
System.out.print(temp[j]);
}
System.out.print(" ");
}
}
1. import java.util.HashMap;
2. import java.util.Map;
3. import java.util.Set;
4.
5. public class DuplicateCharFinder {
6. public void findIt(String str) {
7. Map<Character, Integer> baseMap = new HashMap<Character, Integer>();
8. char[] charArray = str.toCharArray();
9. for (Character ch : charArray) {
10. if (baseMap.containsKey(ch)) {
11. baseMap.put(ch, baseMap.get(ch) + 1);
12. } else {
13. baseMap.put(ch, 1);
14. }
15. }
16. Set<Character> keys = baseMap.keySet();
17. for (Character ch : keys) {
18. if (baseMap.get(ch) > 1) {
19. System.out.println(ch + " is " + baseMap.get(ch) + " times");
20. }
21. }
22. }
23.
24. public static void main(String a[]) {
25. DuplicateCharFinder dcf = new DuplicateCharFinder();
26. dcf.findIt("India is my country");
27. }
28. }
Output:
is 3 times
i is 2 times
n is 2 times
y is 2 times
2.> how to count occurance of each character in a string in java.
class EachCharCountInString
{
static void characterCount(String inputString)
{
//Creating a HashMap containing char as a key and occurrences as a value
charCountMap.put(c, charCountMap.get(c)+1);
}
else
{
//If char is not present in charCountMap,
//putting this char to charCountMap with 1 as it's value
charCountMap.put(c, 1);
}
}
System.out.println(charCountMap);
}
characterCount("All Is Well");
Output :
{E=4, 2=2, v=2, =4, P=1, S=1, a=4, J=5}
{W=1, =2, e=1, s=1, A=1, l=4, I=1}
{D=1, d=1, =2, G=1, e=2, A=1, n=3, o=2}
Note :
Above program is a case sensitive i.e it treats ‘A’ and ‘a’ as two different characters. If you want
your program not to be case sensitive, convert the input string to either lowercase or uppercase
using toLowerCase() or toUpperCase() methods.
3.> how do you remove all white spaces from a string in java.
Output:
IndiaIsMyCountry
IndiaIsMyCountry
package com.includehelp.stringsample;
import java.util.Scanner;
/**
* Easiest way to check Given String is Palindrome String
or not
* @author includehelp
*/
public class PalindromString {
return (inputStr.equalsIgnoreCase(reverseStr));
}
if(isPalindromString(inString)){
System.out.println(inString +" is a Palindrom
String");
}
else{
System.out.println(inString +" is not a
Palindrom String");
}
}
}
Output
First run:
Enter String : india
india is not a Palindrom String
Second run:
Enter String : abcba
abcba is a Palindrom String
5.> how to check if two String are anargms.
class GFG {
return true;
}
int cnt = 0;
if (inp[i] == inp[j]) {
System.out.println(inp[j]);
cnt++;
break;
Program Output:
Duplicate Characters are: s o