1 字符串 ——> 字符数组(char数组)
toCharArray()方法
语法:
public char[] toCharArray()
实例:
public class test {
public static void main(String[] args) {
String str = "HelloWord";
// String ——> 字符数组
char[] arr = str.toCharArray();
// 打印数组
for(int i=0; i<str.length(); i++) {
System.out.print(arr[i]+" "); //H e l l o W o r d
}
}
}
2 字符串(String)——> 字符串数组
split("")和split(" ") 方法
语法:
public String[] split(String regex, int limit)
//参数:
//regex -- 正则表达式分隔符。
//limit -- 分割的份数。
实例:
public class test {
public static void main(String[] args) {
String str = "Hello Word";
// String ——> 字符串数组
String[] arr1 = str.split(""); //单个字符转换为一个字符串数组的元素
String[] arr2 = str.split(" "); //以空格作为分隔符的转换为两个字符串
// 打印数组
for(int i=0; i<arr1.length; i++) {
System.out.print(arr1[i]+" "); //H e l l o W o r d
}
System.out.println();
for(int i=0; i<arr2.length; i++) {
System.out.println(arr2[i]);
}
}
}
3 **** ——> 字符串
valueOf() 方法
valueOf() 方法不同的表现形式:
- valueOf(boolean b): 返回 boolean 参数的字符串表示形式。
- valueOf(char c): 返回 char 参数的字符串表示形式。
- valueOf(char[] data): 返回 char 数组参数的字符串表示形式。
- valueOf(char[] data, int offset, int count): 返回 char数组参数的特定子数组的字符串表示形式。
- valueOf(double d): 返回 double 参数的字符串表示形式。
- valueOf(float f): 返回 float 参数的字符串表示形式。
- valueOf(int i): 返回 int 参数的字符串表示形式。
- valueOf(long l): 返回 long 参数的字符串表示形式。
- valueOf(Object obj): 返回 Object 参数的字符串表示形式。
语法:
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(char[] data)
static String valueOf(char[] data, int offset, int count)
static String valueOf(double d)
static String valueOf(float f)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(Object obj)
实例:
public class test {
public static void main(String[] args) {
boolean a = true;
char b = 'b';
char[] c = {'a','b','c'};
double d = 100.01;
System.out.println(String.valueOf(a));
System.out.println(String.valueOf(b));
System.out.println(String.valueOf(c));
System.out.println(String.valueOf(d));
}
}
4 字符串数组 ——> 字符串
只能通过 for 循环
直接实例:
public class test {
public static void main(String[] args) {
String[] str = {"ab","cd","ef"};
StringBuffer sb = new StringBuffer();
for(int i = 0; i < str.length;i++){
sb.append(str[i]);
}
String s = sb.toString();
System.out.println(s);
}
}
5 整型 ——> 字符串
1.1 valueOf方法
valueOf(int i): 返回 int 参数的字符串表示形式。
语法:
static String valueOf(int i)
实例:
int a = 1234;
System.out.println(String.valueOf(a));
1.1 toString()方法
语法:
static String toString(int i)
//i: 要转换的整数。
//toString(int i): 返回表示指定 int 的 String 对象。
实例:
int a = 1234;
String str = Integer.toString(a);
6 字符串 ——> 整型
直接实例:
String str = "1234";
int a = Integer.valueOf(str).intValue();