Java中常用的API

1. 字符串与数字之间的相互转换

① 将数字转化为字符串:

String s = Integer.toString(int n);

String s = Double.parseDouble(s);

 

② 将数字型的字符串转化为数字

int n = Integer.parseInt(String s)

double n = Double.parseDouble(s)

public class Main {
	public static void main(String[] args) {
		String s = "123456";
		int n1 = Integer.parseInt(s);
		System.out.println(n1);
		
		int n2 = 234812;
		s = Integer.toString(n2);
		
		System.out.println(s);
		double n3 = 23.45;
		
		s = Double.toString(n3);
		System.out.println(s);
		
		s = "45.87";
		System.out.println(Double.parseDouble(s));
	}
}

 

2. String对象与char数组的转换

① 字符串对象转为char类型的数组

char arr[] = s.toCharArray();

 

② 将char类型的数组转为字符串

String s = new String(char arr[]);

String s = String.valueOf(char arr[]);

public class Main {
	public static void main(String[] args) {
		String s = "123345";
		char arr[] = s.toCharArray();
		for(int i = 0; i < arr.length; i++){
			System.out.print(arr[i]);
		}
		System.out.print("\n");
		char arr2[] = {'a', 'b', 'c', 'd', 'e'};
		s = new String(arr2);
		System.out.println(s);
		
		char arr3[] = {'e', 'f', 'g', 'h', 'i'};
		s = String.valueOf(arr3);
		System.out.println(s);
	}
}

3. 根据索引获取字符和根据字符获取索引

① 根据索引获取字符:

char c = s.charAt(i);

 

② 获取字符的最后一个下标(可能有多个重复的字符):

int index = s.lastIndexOf(char c);

获取字符的第一个下标:

int index = s.indexOf(char c);

public class Main {
	public static void main(String[] args) {
		String s = "abbc";
		char c = s.charAt(3);
		System.out.println(c);
		System.out.println(s.indexOf('b'));
		System.out.println(s.lastIndexOf('b'));
	}
}

 

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |