创建字符串:1. String(char a[]) char a[] = {'g','o','o','d'}; String str = new String(a); 2. String(char a[],int offset,int length) char a[] = {'s','t','u','d','e','n','t'}; String str = new String(a,2,4); 3. 通过字符串常量的引用赋值给一个字符串变量: String str1,str2; str1 = "good"; str2 = "good"; str1和str2共用一个"good"内存空间。 连接多个字符串String s1 = new String("hello"); String s2 = new String("world"); String string = s1 " " s2; System.out.println(string); 换行输出: System.out.println("hello " "world");
获取字符串信息获取字符串长度 str.length(); 字符串查找 String类提供了两种查找字符串的方法,即indexOf()与lastIndexOf()方法。这两种方法都允许在字符串中搜索指定条件的字符或字符串。indexOf()方法返回的是搜索的字符或字符串首先出现的位置,lastIndexOf()方法返回的是搜索的字符或字符串最后一次出现的位置。 str.indexOf(substr); //str:任意字符串对象 //substr:要搜索的字符串 获取指定索引位置的字符 str.charAt(int index); 字符串操作获取子字符串 str.substring(int beginIndex); // 从某一索引处开始截取字符串 str.substring(int beginIndex,int endIndex); // 从beginIndex开始到endIndex结束截取字符串 去除空格 str.trim(); 字符串替换 str.replace(char oldChar,char newChar); 判断字符串的开始与结尾 startsWith()方法与endsWith()方法分别用于判断字符串是否以指定的内容开始或结束。返回值都为Boolean类型。 str.startsWith(String prefix); Str.endsWith(String suffix); 判断字符串是否相等 str.equal(String otherstr); // 区分大小写 str.equalsIgnoreCase(String otherstr); // 不区分大小写 按字典序比较两个字符串 str.compareTo(String otherstr); 大小写转换 str.toLowerCase(); str.toUpperCase(); 字符串分割 str.split(String sign); str.split(String sign,int limit); // limit限制分割次数来源:http://www./content-1-106801.html |
|