Java String character extraction

Introduction

String class has method to extract characters from a String object.

char charAt(int where) 

For example,

char ch;  
ch = "abc".charAt(1); 

assigns the value b to ch.

To extract more than one character at a time, use the getChars() method.

It has this general form:

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) 

The following program demonstrates getChars():

public class Main {
  public static void main(String args[]) {
    String s = "This is a demo of the getChars method.";
    int start = 10;
    int end = 14;
    char buf[] = new char[end - start];

    s.getChars(start, end, buf, 0);//  w  w w.j av a2 s  .co  m
    System.out.println(buf);
  }
}
public class Main 
{
   public static void main(String[] args)
   {/*www.  ja v a  2s  . c  om*/
      String s1 = "hello there";
      char[] charArray = new char[5];

      System.out.printf("s1: %s", s1);

      // test length method
      System.out.printf("\nLength of s1: %d", s1.length());

      // loop through characters in s1 with charAt and display reversed
      System.out.printf("%nThe string reversed is: ");

      for (int count = s1.length() - 1; count >= 0; count--)
         System.out.printf("%c ", s1.charAt(count));

      // copy characters from string into charArray
      s1.getChars(0, 5, charArray, 0);
      System.out.printf("%nThe character array is: ");

      for (char character : charArray)
         System.out.print(character);

      System.out.println();
   } 
}

Java String iterate over the Characters of a String


public class Main {    
    /*from  w ww. j  a v a  2 s.  co m*/
    public static void main(String[] args){

        String str = "test from demo2s.com";
        
        System.out.println(str);
        
        for (char chr:str.toCharArray()){
            System.out.println(chr);
        }
        
        for (int x = 0; x <= str.length()-1; x++){
            System.out.println(str.charAt(x));
        }
    }
    
   
}



PreviousNext

Related