Java:实例

来源:互联网 发布:中国it从业人数 编辑:程序博客网 时间:2024/05/21 17:30

1. Java开始

public class HelloWorld{    public static void main(String[] args){        System.out.println("Hello world.");    }   }//编译,执行$ javac HelloWorld.java $ java HelloWorld Hello world.

2. 字符串处理

2.1 字符串比较

public class StringCompare{    public static void main(String[]  args){        String str = "Hello World.";        String another_str = "hello world.";        Object objStr = str;        System.out.println(str.compareTo(another_str));        System.out.println(str.compareToIgnoreCase(another_str));        System.out.println(str.compareTo(objStr.toString()));        }   }// $ java StringCompare-3200

2.2 字符串查找

public class StringCompare2{    public static void main(String[]  args){        String str_orig = "Hello world, Hello reader.";        int last_index = str_orig.lastIndexOf("Hello");        if(last_index == -1){            System.out.println("Not Found");        }           else{            System.out.println("Last occurrence of index is " + last_index);        }           }   }// Last occurrence of index is 13

2.3 删除字符串中一个字符

public class RemoveChar{    public static void main(String[]  args){        String str = "This is a line.";        System.out.println(removeChar(str, 3));    }       public static String removeChar(String s, int pos){        String newStr = s.substring(0, pos) + s.substring(pos + 1);         return newStr;    }   }//$ javac RemoveChar.java//$ java RemoveCharThi is a line.

2.4 字符串替换

public class StringReplace{    public static void main(String[] args){        String str = "Hello World. Hello";        System.out.println(str.replace('H', 'W'));        System.out.println(str.replaceFirst("He", "We"));        System.out.println(str.replaceAll("He", "We"));    }   }//Wello World. WelloWello World. HelloWello World. Wello

2.5 字符串反转

public class StringReverse{    public static void main(String[]  args){        String str = "Hello World";        String reverse = new StringBuffer(str).reverse().toString();        System.out.println("Reverse string is :" +  reverse);        }   }//Reverse string is :dlroW olleH

2.6 字符串搜索

        String str = "Hello, Java.";        int intIndex = str.indexOf("Hello");        System.out.println(intIndex);        // 0

2.7 字符串分隔

        String str1 = "www.baidu.com";        String[] temp;        String delimter = "\\.";  // . 需要转义        temp = str1.split(delimter);        for(String s : temp){            System.out.println(s);        }//wwwbaiducom

2.8 字符串大小写转换

        String str2 = "www.baidu.com";        String strUp = str2.toUpperCase();        String strLower = strUp.toLowerCase();        System.out.println("str2 : " + str2);        System.out.println("strUp : " + strUp);        System.out.println("strLower : " + strLower);//str2 : www.baidu.comstrUp : WWW.BAIDU.COMstrLower : www.baidu.com




0 0
原创粉丝点击