Friday, January 2, 2015

Java: Set char at a particular position in a String

There a several ways to set a char at a particular position in a String.

String str = "IloveJavaProgramming"

1. Use the method setCharAt in StringBuilder. 
   
      StringBuilder sb = new StringBuilder(str);
      sb.setCharAt(2, 'i');
      sb.setCharAt(3, 'k');

      System.out.println(sb.toString());
   
      The output will be: IlikeJavaProgramming

2. Connect sub Strings.

      str.substring(0,2) + "ik" + str.substirng(4);

3. Use char array.

      char[] sa = str.toCharArray();
      sa[2] = 'i';
      sa[3] = 'k';
   
      str = new String(sa);

----------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

      

No comments:

Post a Comment