Advertisement
Guest User

StringLib.java

a guest
Jul 14th, 2011
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. import java.util.Hashtable;
  2.  
  3.  
  4. public class StringLib {
  5.    
  6.     public static Character firstNonRepeated(String str){
  7.        
  8.         int[] strA=new int[128];
  9.         for (int i=0; i<strA.length;i++){
  10.             strA[i]=0;
  11.         }
  12.                
  13.         for (char c: str.toCharArray()){
  14.             strA[c]++;         
  15.         }
  16.        
  17.         for (char c: str.toCharArray()){
  18.             if (strA[c]==1)
  19.                 return new Character(c);
  20.         }
  21.        
  22.         return null;
  23.    
  24.     }
  25.    
  26.     public static Character firstNonRepeated2(String str){
  27.        
  28.         Hashtable<Character,Integer> hash=new Hashtable<Character,Integer>();
  29.         Character ch;
  30.         Integer intgr;
  31.        
  32.         for (char c: str.toCharArray()){
  33.             ch=new Character(c);
  34.             intgr=(Integer)hash.get(ch);
  35.             if (intgr==null)
  36.                 hash.put(ch, new Integer(1));
  37.             else
  38.                 hash.put(ch, new Integer(intgr.intValue()+1));
  39.         }
  40.        
  41.         for (char c: str.toCharArray()){
  42.             ch=new Character(c);
  43.             intgr=(Integer)hash.get(ch);
  44.             if (intgr==1)
  45.                 return ch;
  46.         }
  47.        
  48.         return null;
  49.    
  50.     }
  51.    
  52.     public static void main(String[] args){
  53.         String str="long string with all sorts of punctuation! hello there ; ?";
  54.        
  55.         System.out.println("Fcn1: The first nonrepeated character of "+ str+" is: "+ StringLib.firstNonRepeated(str));
  56.         System.out.println("Fcn2: The first nonrepeated character of "+ str+" is: "+ StringLib.firstNonRepeated2(str));
  57.            
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement