java里数字,字符串相关
类型之间的转换
数字转字符串
方法1: 使用String类的静态方法valueOf
方法2: 先把基本类型装箱为对象,然后调用对象的toString
package digit;
public class TestNumber {
public static void main(String[] args) {
int i = 5;
//方法1
String str = String.valueOf(i);
//方法2
Integer it = i;
String str2 = it.toString();
}
}
字符串转数字
调用Integer的静态方法parseInt
package digit;
public class TestNumber {
public static void main(String[] args) {
String str = "999";
int i= Integer.parseInt(str);
System.out.println(i);
}
}
一些数学常用的东西
public static void main(String[] args) {
float f1 = 5.4f;
float f2 = 5.5f;
//5.4四舍五入即5
System.out.println(Math.round(f1));
//5.5四舍五入即6
System.out.println(Math.round(f2));
//得到一个0-1之间的随机浮点数(取不到1)
System.out.println(Math.random());
//得到一个0-10之间的随机整数 (取不到10)
System.out.println((int)( Math.random()*10));
//开方
System.out.println(Math.sqrt(9));
//次方(2的4次方)
System.out.println(Math.pow(2,4));
//π
System.out.println(Math.PI);
//自然常数
System.out.println(Math.E);
}
格式化输出
%s 表示字符串
%d 表示数字
%n 表示换行
//直接使用+进行字符串连接,编码感觉会比较繁琐,并且维护性差,易读性差
String sentence = name+ " 在进行了连续 " + kill + " 次击杀后,获得了 " + title +" 的称号";
System.out.println(sentence);
//使用格式化输出
//%s表示字符串,%d表示数字,%n表示换行
String sentenceFormat ="%s 在进行了连续 %d 次击杀后,获得了 %s 的称号%n";
System.out.printf(sentenceFormat,name,kill,title);
字符串相关操作
String sentence = “盖伦,在进行了连续8次击杀后,获得了 超神 的称号”;
- charAt(int index)获取指定位置的字符
- toCharArray();获取对应的字符数组char [] sc = sentence.toCharArray();
- //截取从第3个开始的字符串 (基0)
//到5-1的位置的字符串
//左闭右开
String subString2 = sentence.substring(3,5); - sentence.split()根据分隔符进行分隔,得到的结果不包含分隔符
- sentence.trim() 去掉首尾空格
- sentence.toLowerCase() 全部变成小写,sentence.toUpperCase() 全部变成大写
- System.out.println(sentence.indexOf(‘8’)); //字符第一次出现的位置
System.out.println(sentence.indexOf(“超神”)); //字符串第一次出现的位置
System.out.println(sentence.lastIndexOf(“了”)); //字符串最后出现的位置
System.out.println(sentence.indexOf(’,’,5)); //从位置5开始,出现的第一次,的位置
System.out.println(sentence.contains(“击杀”)); //是否包含字符串"击杀" - replaceAll(“被替换的内容”,“新内容”) 替换所有的
- replaceFirst(“被替换的内容”,“新内容”) 只替换第一个
- 使用str1.equals(str2);进行字符串内容的比较,必须大小写一,str1.equalsIgnoreCase(str2),忽略大小写判断内容是否一致
- str.startsWith(“内容”) //是否以…开始,str.endsWith(“内容”) //是否以…结束
以下内容需要用到StringBuffer
StringBuffer sb = new StringBuffer(str1); //根据str1创建一个StringBuffer对象
- sb.append(“be light”); //在最后追加
- sb.delete(4, 10);//删除4-10之间的字符
- sb.delete(4, 10);//删除4-10之间的字符
- sb.insert(4, "there ");//在4这个位置插入 there
- sb.reverse(); //反转
- System.out.println(sb.length()); //内容长度
System.out.println(sb.capacity());//总空间