Q1. How to reverse a String in java?
Solution:-
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args)
{
String input="";
System.out.println("Enter the input String");
Scanner in = new Scanner(System.in);
input = in.nextLine();
char[] chr=input.toCharArray();
for(int i=chr.length-1; i>=0; i--)
System.out.print(chr[i]);
}
}
Output:-
Enter the input String
Ankit
tiknA
Q2. How to find the first non repeated character in the String?
Soution:-
import java.util.HashMap;
import java.util.Scanner;
public class FirstNonRepated {
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println(" Please enter the input string :" );
Scanner in = new Scanner (System.in);
String s=in.nextLine();
char c=firstNonRepeatedCharacter(s);
System.out.println("The first non repeated character is : " + c);
}
public static Character firstNonRepeatedCharacter(String str)
{
HashMap<Character,Integer> characterhashtable=
new HashMap<Character ,Integer>();
int i,length ;
Character c ;
length= str.length();
for (i=0;i < length;i++)
{
c=str.charAt(i);
if(characterhashtable.containsKey(c))
{
// increment count corresponding to c
characterhashtable.put( c , characterhashtable.get(c) +1 );
}
else
{
characterhashtable.put( c , 1 ) ;
}
}
for (i =0;i < length;i++ )
{
c= str.charAt(i);
if( characterhashtable.get(c) == 1 )
return c;
}
return null ;
}
}
OutPut:-
Please enter the input string :
Ankit
The first non repeated character is : A

0 comments:
Post a Comment