java 字符串使用总结

it2022-05-09  35

java 字符串使用总结

需要依赖:

<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency> /** * 获取字符串包含某个指定字符串的个数 */ String str = "111-2132121211-12"; String t = "-"; int i = StringUtils.countMatches(str, t); System.out.println("str字符串包含:"+ i + "个 -"); /** * 获取指定字符串在字符串中第一次出现的索引位置 */ int index = str.indexOf(t); System.out.println(index); /** * 判断字符串是否包含某个指定的字符串 */ boolean contains = str.contains(t); System.out.println(contains); /*StringBuffer buffer = new StringBuffer("123456"); System.out.println(buffer.toString());//输出123456 buffer.replace(0, 1, "a"); System.out.println(buffer.toString());//输出a23456*/ /** * 替换指定索引字符串,指定字符串索引包前不包后; */ String s = "111-2132121211-12"; int matches = StringUtils.countMatches(s, "-"); if (matches > 1){ StringBuffer buffer = new StringBuffer(s); int lastIndexOf = s.lastIndexOf("-"); buffer.replace(lastIndexOf, lastIndexOf+1, "/"); s = buffer.toString(); } System.out.println(s);

执行结果:


最新回复(0)