学习小结
范例 16-8 分析字符串与字符数组互相转换
package com.Javastudy2;
/**
* @author Y.W.
* @date 2018年5月29日 上午12:35:14
* @Description TODO 分析字符串与字符数组互相转换
*/
public class P423_16_8 {
public static void main(String[] args) {
String str = "hellojava"; // 直接赋值法
char[] data = str.toCharArray(); // 将字符串变成字符数组
for (int x = 0; x < data.length; x++) {
System.out.print(data[x] + "、");
data[x] -= 32; // 小写变成大写
}
System.out.println();
System.out.println("将全部字符数组变为字符串:" + new String(data));
// 取得部分内容的时候需要设置起始点和取得的长度
System.out.println("将部分字符数组变成字符串:" + new String(data, 5, 4));
}
}
运行结果:
- 字节与字符串
序号 | 方法名称 | 类型 | 描述 |
---|---|---|---|
1 | public String(byte[] bytes) | 构造 | 将全部字节数数组变成字符串 |
2 | public String(byte[] bytes, int offset, int length) | 构造 | 将部分字节数变成字符串 |
3 | public byte[] getBytes() | 普通 | 将字符串变成字节数组 |
4 | public byte[] getBytes(String charsetName) throws UnsupportedEncodingException | 普通 | 将字符串转码 |
范例 16-9 分析字符串与字节相互转换
package com.Javastudy2;
/**
* @author Y.W.
* @date 2018年5月29日 上午12:53:58
* @Description TODO 分析字符串与字节相互转换
*/
public class P424_16_9 {
public static void main(String[] args) {
String str = "hellojava"; // 直接赋值法
byte[] data = str.getBytes(); // 将字符串变成byte数组
for (int x = 0; x < data.length; x++) {
data[x] -= 32;
}
System.out.println(new String(data)); // 将全部byte数组变为字符串
System.out.println(new String(data, 5, 4)); // 将部分字byte数组变成字符串
}
}
运行结果:
- 字符串查找方法
范例 16-10 分析字符串查找方法
package com.Javastudy2;
/**
* @author Y.W.
* @date 2018年5月29日 上午1:05:17
* @Description TODO 分析字符串查找方法
*/
public class P425_16_10 {
public static void main(String[] args) {
String str = "**hello$$world##"; // 直接赋值法
if (str.contains("hello")) { // 查找hello是否存在
System.out.println("内容存在,已查找到!");
}
if (str.indexOf("r") != -1) { // 查找r是否存在
System.out.println("内容存在,字符串位置:" + str.indexOf("r"));
}
if (str.indexOf("o", 6) != -1) { // 由指定位置开始查找o是否存在
System.out.println("内容存在,字符串位置:" + str.indexOf("o", 6));
}
if (str.lastIndexOf("w", 12) != -1) { // 由指定位置由后向前开始查找o是否存在
System.out.println("内容存在,字符串位置:" + str.lastIndexOf("w", 12));
}
System.out.println(str.startsWith("**")); // 判断字符串的其实内容
System.out.println(str.startsWith("$$", 7));
System.out.println(str.endsWith("##"));
}
}
运行结果:
- 字符串替换
范例 16-11 分析字符串替代法
package com.Javastudy2;
/**
* @author Y.W.
* @date 2018年5月29日 上午1:24:34
* @Description TODO 分析字符串替代法
*/
public class P427_16_11 {
public static void main(String[] args) {
String str = "helloworld";
System.out.println(str.replaceAll("o", "***")); // 所有子串出现的位置都替换
System.out.println(str.replaceFirst("l", "_")); // 替换第一个出现的子串
}
}
运行结果:
思考
最近,思想波动,开始思考自己的学习力,又有点迷茫了。
记于2018年5月29日01:31:37
BY Yvan