Tuesday, March 6, 2018

String

public static void main(String[] args){

        // create string with the constructor of string class and print the string
        System.out.println("Example of declearing string : \n");
        String str = "I am a constractor string";
        String str1 = new String("I am also a constructor string");
        System.out.println(str + "\n" + str1  +"\n");


        System.out.println("How to find length of a string : \n");
        // how to find length of a constructor
        //using length(); method we can find length of any string
        String str3 = "Can you find my length please ?";
        int len = str3.length();
        System.out.println("The length of 'str3' is "+ len +"\n");


        System.out.println("How to Reverse a string : \n");
        //how to reverse a string
        //we can reverse a string using ' reverse() ' method
        // reverse() is a method of StringBuffer class
        StringBuffer str4 = new StringBuffer("Reverse me");
        System.out.println("Original string is -> "+ str4);
        String str5 = str4.reverse().toString();
        System.out.println("The string after reverse is -> "+ str5 +"\n");


        System.out.println("How to Iterate every element of a string : \n");
        // to iterate any strings element we need " charAt() " method
        String str6 = "Saiful";
        //print string element individually with a new line
        for(int i=0; i<str6.length(); i++){
            System.out.println(str6.charAt(i));
        }
        System.out.println();

        System.out.println("How to remove all whitespace before a string (using trim()) method : \n");
        //we can do it using trim() method
        String str7 = "    Mukta";
        System.out.print("The string before removing whitespace : ->"+ str7 +"\n");
        System.out.println("The string after removing whitespace : ->"+ str7.trim() +"\n");


        System.out.println("How to break a string into tocken :");
        // bye using " StringTokenizer " class we can break a string into tocken
        /* if a string is " My name is mukta " then it will break into 3 word like
            (1) My
            (2) name
            (3) is
            (4) mukta
        */
        //for that we need a string of stringtokenizer class and hasMoreToken() and nextToken() method
        StringTokenizer str8 = new StringTokenizer("My name is mukta");
        while(str8.hasMoreTokens()){
            System.out.println(str8.nextToken());
        }
        System.out.println();

    }

No comments:

Post a Comment

কম্পিউটার প্রোগ্রামিং শেখা কতটা গুরুত্বপূর্ণ ?

প্রোগ্রামিং কতটা গুরুত্বপূর্ণ? কম্পিউটার বিজ্ঞানের অনেক বড় একটা অংশ জুড়েই রয়েছে প্রোগ্রামিংয়ের দখল। প্রোগ্রামিং ছাড়া আমর...