1795 字
2 分钟
Java字符串操作
Java考试前的补天
String
判断字符串相等
//判断字符串相等String s = "abc";if(s.equals("abc")){ System.out.println("字符串相等");}取某个位置的字符
常用于遍历字符串
String str = "hello";char ch = str.charAt(0); //'h'长度
str.length() //字符串长度arr.length //数组长度list.size() //集合长度判断是否包含
String str = "hello world";if(str.contains("world")){ System.out.println("包含world");}判断开头结尾
String str = "Hello world";
str.startWith("Hello"); //是否以Hello开头str.endWith("world"); //是否以world结尾截取字符串
String str = "abcdef";String s1 = str.substring(2); //cdefString s2 = str.substring(1,4); //bcd查找位置——indexOf
String str = "hello";
int index = str.indexOf("e");//返回下标1;找不到返回-1替换字符串——replace()
String str = "hello";String newstr = str.replace("l","x");System.out.println(newstr); //hexxo去掉首尾空格——trim()
String str = " hello";str = str.trim(); //"hello"大小写转换
String str = "Hello";System.out.println(str.toUpperCase()); //HELLOSystem.out.println(str.toLowerCase()); //hellochar
判断是否是数字
char ch = '5';if(Character.isDigit(ch)){ System.out.println("是数字");}判断是否是字母
char ch = 'A';if(Character.isLetter(ch)){ System.out.println("是字母");}判断大小写字母
Character.isUpperCade(ch); //是否大写Character.isLowerCase(ch); //是否小写大小写转换
char ch = 'a';char upper = Character.toUpperCase(ch);字符转整数
char ch = 'a';int num = ch - '0';StringBuilder
创建StringBuilder
StringBuilder sb = new StringBuilder()'追加内容
result.append("hello");System.out.println(result.toString());反转字符串——判断回文
StringBuilder sb = new StringBuilder("abc");sb.reverse();System.out.println(sb); //cba//判断回文String str = "aba";
String str2 = new StringBuilder(str).reverse().toString();
if(str.equals(str2)){ System.out.println("是回文");}删除——deleteCharAt()
StringBuilder sb = new StringBuilder("abc");sb.deleteCharAt(1); //ac插入——insert()
StringBuilder sb = new StringBuilder("hllo");sb.insert(1,"e");//hello修改——secCharAt()
StringBuilder sb = new StringBuilder("abc");sb.setCharAt(1,"x"); //axc最后要转String
StringBuilder sb = new StringBuilder();
sb.append("abc");
String result = sb.toString(); 阅读量 加载中
Comments
评论区
欢迎留言,一起交流~