+92 332 4229 857 99ProjectIdeas@Gmail.com

String Manipulation (Java)


Code
Joining A String
Reversing A String
Replacing A Character In String
Removing A Character In String


Joining A String:

public static String join(Collection s, String delimiter) {
        StringBuffer buffer = new StringBuffer();
        Iterator iter = s.iterator();
        while (iter.hasNext()) {
            buffer.append(iter.next());
            if (iter.hasNext()) {
                buffer.append(delimiter);
            }
        }
        return buffer.toString();
    }

      //Joining A String
       ArrayList arl = new ArrayList();
       arl.add("i");
       arl.add("am");
       arl.add("muslim");
       System.out.println(join(arl, ":"));
Output:

      i:am:muslim  //every object in Collection is separated by ":"

Reversing A String:
      
       String strTwo = "pakistan";
       StringBuffer str = new StringBuffer(strTwo);
       System.out.println(str.reverse());
Output:  
      
       natsikap


Replacing a character in a String:

       String strTwo = "pakistan";
       String newStr = strTwo.replace('n', 'i');
       System.out.println(newStr);
Output: 
  
       pakistai //instead of pakistan

Removing a character in a String:

       String value = "i am dangerous";
       int pos = value.length()-5; //minus 5 because to reach "e" and remove it
       String newValue  = value.substring(0,pos) + value.substring(pos+1);
       System.out.println(newValue);
Output: 
  
       i am dangrous //because "e" is removed

Determining a character location: 

       String strOne = "hello";
       int index = strOne.indexOf('l');
       System.out.println(index);
Output:  

       2 //starting from "0"
  

0 comments: