Java基础String的方法
字符串类型写法格式如下: 格式一: String 变量名称; 变量名称=赋值(自定义或传入的变量值); 格式二: String 变量名称=赋值(自定义或传入的变量值);在输出时任何数据类型与字符串进行拼接,结果一般是字符串
1 public class StringFunc { 2 3 public static void main(String[] args){ 4 //字符串拼接 5 String str1; 6 str1 = "hello"; 7 String str2 = " world"; 8 System.out.println(str1+str2); 9 //字符串与整数拼接 10 int num = 100; 11 String socers = "得分:"; 12 System.out.println(socers + num); 13 //字符串与对象拼接 14 StringFunc Test = new StringFunc(); 15 System.out.println(socers + Test); 16 //字符串方法总结 17 String str3 = "abcdef"; 18 System.out.println("length: "+str3.length()); //查看字符串长度 19 System.out.println("concat: "+"xxx".concat("a")); //在结尾默认追加字符串 20 System.out.println("replace: "+"aaa".replace("a","z")); //替换字符串种的字符 21 System.out.println("isEmpty: "+"".isEmpty()); //判断字符串是否为空 22 System.out.println("substring: "+"abcdef".substring(3)); //从首位移除多少个字符 23 System.out.println("substring: "+"abcdef".substring(2,5)); //从字符哪截取到哪 24 System.out.println("length: "+str3.toUpperCase()); //转换小写字母为部大写 25 System.out.println("length: "+"ABCDEF".toLowerCase()); //转换大写字母为小写 26 System.out.println("startsWith: "+"abcd".startsWith("abc")); //判断以什么开头 27 System.out.println("endsWith: "+"edef".endsWith("def")); //判断以什么结尾 28 String[] list = "a,b,c,d".split(","); //字符串根据分隔符转换成列表的操作 29 System.out.println("split: "+list[0]+" "+list[1]+" "+list[2]+" "+list[3]); //打印上面的列表值 30 //以下仅作了解 31 System.out.println("indexOf: "+str3.indexOf(97)); //输入对应ASCII码整数对应字符下标会返回 32 System.out.println("indexOf: "+"abc".indexOf("b")); //判断字符的下标 33 System.out.println("hashCode: "+"123".hashCode()); //为这个字符串生成哈希值 34 System.out.println("charAt: "+str3.charAt(3)); //返回字符串下表对应的单个字符 35 System.out.println("codePointAt: "+str3.codePointAt(1)); //返回字符串对应位置的ASCII码 36 System.out.println("codePointBefore: "+str3.codePointBefore(1)); //查看字符串对应位置前一位的ASCII码 37 System.out.println("codePointCount: "+str3.codePointCount(1,6)); //查看字符串指定下标长度 38 System.out.println("compareTo: "+"z".compareTo("a")); //对比两个字符串相差多少位(利用ASCII码运算差值) 39 } 40 }
具体输出如下:
原文地址:https://www.cnblogs.com/cookie1026/p/9678020.html
时间: 2024-10-07 05:18:40