使用Java的String类操作字符串和子串。

1个回答

  • public class Du02 {

    public static void main(String[] args) {

    String str = "I am a student,I am at ccit";

    System.out.println(str.length());

    System.out.println(str.charAt(0));

    System.out.println(str.charAt(str.length()-1));//

    int firstIndex = str.indexOf(" ");

    System.out.println("First word: " + str.substring(0, firstIndex));

    int lastIndex = str.lastIndexOf(" ");

    System.out.println("Last word: " + str.substring(lastIndex));

    System.out.println(str.replace('c', 'C')); //

    String[] ary = str.replace(",", " ").split("\s+");

    for(int i =0; i < ary.length; i++){

    if(!ary[i].trim().equals("")){

    System.out.println(ary[i].trim());

    }

    }

    System.out.println("String contains ma? " + str.concat(" ma "));

    System.out.println("String starts with 'i', ends with 'i'? " + str.matches("I(.)*I"));

    }

    }

    -----------testing

    27

    I

    t

    First word: I

    Last word: ccit

    I am a student,I am at CCit

    I

    am

    a

    student

    I

    am

    at

    ccit

    String contains ma? I am a student,I am at ccit ma

    String starts with 'i', ends with 'i'? false