1.字符数组转成字符串打印
直接打印字符数组打印的是它的索引地址,应将其转换成字符串打印内容。
char[] charArray = {'H', 'e', 'l', 'l', 'o'};
System.out.println(new String(charArray));
char[] charArray = {'H', 'e', 'l', 'l', 'o'};
System.out.println(String.valueOf(charArray));
2.字符串判断有无子串
可以转成字符串数组一个个遍历,也可以直接使用contains方法。
例子:
String str = "abcdef";
System.out.println(str.contains("de")); //返回true
扩展:
若判断的不是子串而是具体元素,那么不能用contains方法。
例子:判断字符串是否有“猕猴桃”。
String str = "西瓜、菠萝、猕猴桃儿Plus、水蜜桃、柚子、苹果、火龙果";
1.使用contains()方法。本例目标“猕猴桃”,而实际元素是“猕猴桃儿Plus”,应返回false,与实际返回true不符。
System.out.println(str.contains("猕猴桃")); //返回true
2.将元素放入集合中判断。先将 str 转成字符串数组,然后使用 Arrays.asList() 方法转成一个ArrayList,使用它的contains方法来判断。
boolean ret = Arrays.asList(str.split("、")).contains("猕猴桃");
System.out.println(ret); //返回false