在《Java 11 正式发布,这 8 个逆天新特性教你写出更牛逼的代码》一文中,我介绍了Java11的8个新特性,其中我觉得String的增强有点意思,这里单独说一下。Java11增加了一系列字符串处理方法,如下所示。//判断字符串是否为空".isBlank();//true//去除前后空格"Javastack".strip();//"Javastack"//去除尾随空格"Javastack".stripTrailing();//"Javastack"//去掉第一个空格"Javastack".stripLeading();//"Javastack"//复制字符串"Java".repeat(3);//"JavaJavaJava"//行数"A\nB\nC".lines().count();//3最有意思的是repeat和lines方法,来看看怎么玩吧!repeatrepeat方法的作用是将一个字符串重复N次,可以用来替换工具类:org.apache.commons.lang3.StringUtils#repeat(java.lang.String,int),看源码重复代码。publicStringrepeat(intcount){if(count<0){thrownewIllegalArgumentException("countisnegative:"+count);}if(count==1){returnthis;}finalintlen=value.length;if(len==0||count==0){return"";}if(len==1){finalbyte[]single=newbyte[count];Arrays.fill(single,value[0]);returnnewString(single,coder);}if(Integer.MAX_VALUE/count
