欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Java中String字符串操作:深入理解与常用转义字符技巧汇总

最编程 2024-02-10 19:02:57
...
public class Str { public static void main(String[] args) { //.length 数组的属性 String[] ss = new String[]{}; int size = ss.length; String s = "hello-中国人"; //lengtn() String的方法 int len = s.length(); System.out.println(s); System.out.println(len); //字节的个数,utf_8,一个汉字三个字节 int bytesize = s.getBytes(StandardCharsets.UTF_8).length; System.out.println(bytesize);//15 //equals String s1="ok"; String s2="ok"; System.out.println(s1.equals(s2)); //equals 和new比较 //new重新分配地址 String x=new String("ok"); String y=new String("ok"); //==判断是不是同一个对像 System.out.println(x==y); //equals判断值是否一样 System.out.println(x.equals(y)); //equalsIngoreCase忽略大小写比较值大小 System.out.println(x.equalsIgnoreCase(y)); System.out.println("Hello Java".toLowerCase());//转化成小写 System.out.println("Hello Java".toUpperCase());//转换成大写 System.out.println(" java hello "); System.out.println(" java hello ".length());//长度 System.out.println(" java hello ".trim());//清楚两边空格 System.out.println(" java hello ".replace(" ",""));//清楚中间空格 System.out.println(" java hello ".trim().length()); //concat连接字符串 var a="hello"; var b="world"; var c=a.concat(b).concat("java").concat("java-world"); System.out.println(c); //Substring截取字符串,查的是索引号0,1,2... System.out.println(c.substring(3));//截取从3以后的字符串 System.out.println(c.substring(5,7));//截取索引从五到七的字符串(不包括七) //indexOf 和 lastIndexOf 都是返回字符串字符的位置 System.out.println(c.indexOf("WORLD"));//没有为-1 System.out.println(c.indexOf("world"));//从左边开始查 System.out.println(c.lastIndexOf("world"));//从右边开始查,并返回当前索引的位置(当前索引都是从左边开始查) //contains() 是否包含,返回布尔值 System.out.println(c.contains("world")); //split() 将字符串每个字符,组成char[]返回 System.out.println("javaworld".split("")); System.out.println(Arrays.toString("javaworld".split(""))); //charAt() 在那个位置的字符 System.out.println(c.charAt(2)); //startswith 以...开始 //endwish 以...结尾 都返回布尔型 System.out.println(c.startsWith("h")); System.out.println(c.endsWith("v")); //以下为java 11 String 新的API方法 //isBlank()和isEmpty()都返回布尔值 String str=" "; System.out.println(str.isBlank());//true 空格算字符串 System.out.println(str.isEmpty());//false 空格不算字符串 //strip() 去除首尾空格和trim相似 //stripTrailing() 去除尾部空格 //stripLeading() 去除头部空格 System.out.println(" java16 ".strip()); System.out.println(" java16 ".stripTrailing()); System.out.println(" java16 ".stripLeading()); //repeat() 重复 System.out.println("java16".repeat(4)); //lines() 行数 System.out.println("\r\naaa\r\nbbb\r\nccc".lines().count()); //StringBuilder 都支持动态改变字符串 StringBuilder常用 //StringBuffer } }

推荐阅读