java基础 —— 字符串

来源:互联网 发布:mysql删除数据库 编辑:程序博客网 时间:2024/06/11 16:50

1、字符串比较

public class StringCompare {   public static void main(String args[]){      String str = "Hello World";      String anotherString = "hello world";      Object objStr = str;      System.out.println( str.compareTo(anotherString) );      System.out.println( str.compareToIgnoreCase(anotherString) );  //忽略大小写      System.out.println( str.compareTo(objStr.toString()));   }}

运行结果:

-3200

2、通过字符串函数 substring() 函数来删除字符串中的一个字符

public class SubString{   public static void main(String args[]) {      String str = "this is Java";      System.out.println(removeCharAt(str, 3));   }   public static String removeCharAt(String s, int pos) {      return s.substring(0, pos) + s.substring(pos + 1);   }}

运行结果:

thi is Java

3、合并两个字符串

iimport java.util.*;public class StringCombine {        public static void main(String[] args) {        String str1 = "001,002,003,005,006";        String str2 = "004,005,006";        String str = "";        TreeSet ts = new TreeSet();        String[] result1 = str1.split(",");        for(int i=0; i<result1.length; i++) {            ts.add(result1[i]);        }        String[] result2 = str2.split(",");        for(int i=0; i<result2.length; i++) {            ts.add(result2[i]);        }        Iterator it = ts.iterator();        while(it.hasNext()) {            str = str + it.next();            if(it.hasNext()) {                str = str + ",";            }        }        System.out.println(str);    }}

运行结果:

001,002,003,004,005,006
0 0
原创粉丝点击