目录
练习1:String字符输出
输入一段字符串“good good study”输出为“yduts doog doog”或者“doog doog yduts”
方式一:yduts doog doog
package com.jt.string;
public class TestStringApi {
public static void main(String[] args) {
//1.创建一个字符串
String str = "good good study";
//2.创建一个StringBuilder对象
StringBuilder sb = new StringBuilder(str);
//3.使用reverse()方法反向输出
sb.reverse();
//4.类型转换
String s = sb.toString();
//5.输出
System.out.println(s);
}
}
方式二:doog doog yduts
package com.jt.string;
public class TestStringApi {
public static void main(String[] args) {
//1.创建一个字符串和一个空串
String str = "good good study";
String s = "";
//2.将字符串按照“ ”(空格)拆分,得到一个strs数组
String[] strs = str.split(" ");
//3.遍历这个数组
for (int i = 0; i < strs.length; i++) {
//4.将这个数组的下标字符串元素在数组化
char[] chars = strs[i].toCharArray();
//5.遍历这个子数组,并进行换位
for (int j = 0; j < chars.length/2; j++) {
char temp = chars[j];
chars[j] = chars[chars.length-1-j];
chars[chars.length-1-j] = temp;
}
//6.将各个子数组字符串转换
strs[i] = String.valueOf(chars);
//将字符串输出
s += strs[i]+" ";
}
System.out.println(s);
}
}
练习2:将int[ ]中的元素输出为字符串的格式
例:int[ ] i = {1,2,3,4,5,6} 输出为:[1,2,3,4,5,6] 字符串格式
方法一:
package com.jt.string;
public class TestStringApi {
public static void main(String[] args) {
//1.创建一个数组
int[] in = {1,2,3,4,5,6};
//2.创建一个StringBuilder对象
StringBuilder str = new StringBuilder();
//3.在字符串的首端加入一个[
str.append("[");
//4.遍历数组
for (int j = 0; j < in.length; j++) {
if (j<in.length-1){
//5.转化数组元素
str.append(in[j]+",");
}else {
str.append(in[j]+"]");
}
//打印hash值
System.out.println(str.hashCode());
}
//输出对象
System.out.println(str.toString);
}
}
21685669
21685669
21685669
21685669
21685669
21685669
[1,2,3,4,5,6]
Process finished with exit code 0
方法二:
package com.jt.string;
public class TestStringApi {
public static void main(String[] args) {
//1.创建一个数组
int[] in = {1,2,3,4,5,6};
//2.创建一个String "["串
String str = "[";
//3.遍历数组
for (int j = 0; j < in.length; j++) {
if (j<in.length-1){
//5.转化数组元素
str +=in[j]+",";
}else {
str +=in[j]+"]";
}
//打印hash值
System.out.println(str.hashCode());
}
//输出对象
System.out.println(str);
}
}
89014
85544048
603453129
97873665
-432686760
799853119
[1,2,3,4,5,6]
Process finished with exit code 0
练习3:将String str = "name=小明 age=18 sonId";给Student类属性赋值
package com.jt.string;
public class TestStringApi {
public static void main(String[] args) {
//1.创建学生对象
Student student = new Student();
//2.创建字符串
String str = "name=小明 age=18 sonId";
//3.使用String的split分割
String[] s = str.split(" ");
//4.遍历分割的字符数组
for (int i = 0; i < s.length; i++) {
//5.使用String的substring方法截取使用indexOf获取截取位置+1,“=”号不要,所以加一
s[i] = s[i].substring(s[i].indexOf("=")+1);
}
//6.赋值
student.name = s[0];
//7.将age的值类型转换
student.age = Integer.valueOf(s[1]);
student.sonId = s[2];
System.out.println(student);
}
}
class Student{
public String name;
public Integer age;
public String sonId;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", classNo='" + sonId + '\'' +
'}';
}
}