——- android培训、java培训、期待与您交流! ———-
String类
String类适用于描述字符串事物。
那么它就提供了多个方法对字符串进行操作。
注意:String s = “”;和String s = null;是不同的,前者指向对象,后者为空
常见的操作有哪些?
1,获取。
1.1 字符串中包含的字符数,也就是字符串的长度。
int length();获取长度
(注意:获取数组的长度arr.length,获取字符串长度s.length(),数组是不带括号的)
1.2 根据位置获取字符串的某个字符。
char charAt(int index);
1.3 根据字符获取该字符在字符串中的位置。
int indexOf(int ch);返回的是ch在字符串中第一次出现的位置。若找不到字符,返回-1
int indexOf(int ch,int fromIndex);从fromIndex指定位置开始(包括fromIndex位置),
获取ch在字符中出现的位置。若找不到字符,返回-1
int indexOf(String str);返回的是str在字符串中第一次出现的位置。若找不到字符,返回-1
int indexOf(String str,int fromIndex);从fromIndex指定位置开始(包括fromIndex位置)
int lastIndexOf(int ch);和indexOf一样,只不过是反向查找
2,判断。
2.1 字符串中是否包含某个子串。
boolean contains(String str);
特殊之处:indexOf(String str):可以索引第一次出现位置,如果返回-1,表示该str不存在
所以,也可以用于对指定判断是否包含。
如:if(str.indexOf(“aa”) == -1)表示不包含”aa”这个字符串。
而且该方法既可以判断是否包含,又可以获取出现位置。
2.2 字符串中是否有内容。
boolean isEmpty();原理就是判断长度是否为0
2.3 字符串是否以指定的内容开头。
boolean startsWith(String str);
2.4 字符串是否以指定的内容结束。
boolean endsWith(String str);
2.5 判断字符串内容是否相同。复写了Object类中的equals方法。
boolean equals(String str);
2.6 判断内容是否相同,并忽略大小写
boolean equalsIgnoreCase(String str);
3,转换
3.1 将字符数组转成字符串。
构造函数:String(char[]);
String(char[],offset,count);将字符数组中从offset开始,转换count个字符
静态方法:static String copyValueOf(char[]);
static String copyValueOf(char[],offset,count);
static String valueOf(char[]);
static String valueOf(char[],offset,count);
3.2 将字符串转成字符数组。(重点)
char[] toCharArray();
3.3 将字节数组转成字符串。
String(byte[]);
String(byte[],offset,count);将字节数组中从offset开始,转换count个字符
3.4 将字符串转成字节数组。
byte[] getBytes();
3.5 将基本数据类型转换成字符串。
static String valueOf(int);
static String valueOf(duoble);
123+”” 将基本数据类型加上一个空字符串,这样也可以转换成字符串。
特殊:字符串和字节数组在转换过程中,是可以指定编码表的
4,替换
String replace(要特换的字符或字符串,新的字符或字符串); 如果被替换的字符串不存在,则返回原来的字符串
5,切割
String[] split(要切割的字符);
6,子串
获取子串中的一部分。
7,大小写转换,去除空格,比较。
7.1 将字符串转换成大写或者小写
String toUpperCase();转换成大写
String toLowerCase();转换成小写
7.2 将字符串两端的多个空格去除
String trim();
7.3 对两个字符串进行自然顺序比较
int compareTo(String);
代码示例:
public class Demo {
public static void method_7(){
String str = " Hello Java ";
String str1 = str.toUpperCase();//大写
String str2 = str.toLowerCase();//小写
String str3 = str.trim();//去除字符串两端空格
print(str);// ____Hello Java ___
print(str1);// ____HELLO JAVA ___
print(str2);// ____hello java ____
print(str3);//Hello Java
String st1 = "abc";
String st2 = "aaa";
print(st1.compareTo(st2));// 1 如果st1大于st2则返回整数,否则返回负数,等于返回0
}
public static void method_ZiChuan(){
String str = "abcdefg";
String str1 = str.substring(2);//cdefg 从指定位置开始到结尾。如果角标不存在,会出现字符串角标越界异常StringIndexOutBoundsException()
String str2 = str.substring(2,4);//cd 返回的字符串包含头,不包含尾。
print(str1);
print(str2);
}
public static void method_QieGe(){
String str = "zhangsan,lisi,wangwu";
String str1[] = str.split(",");//把逗号给切割掉
for(int i=0;i<str1.length;i++)
print(str1[i]);
}
public static void method_TiHuan(){
String str = "hello java";
String str1 = str.replace("java", "haha");//将java替换成haha
print(str);//结果hello java
print(str1);//结果hello haha
}
public static void method_ZhuanHuan(){
char chr[] = {'a','b','c','d','e','f'};
String str = new String(chr);//将字符数组转换成字符串
print(str);//abcdef
String s = "qwert";
char ch[] = s.toCharArray();//将字符串转成字符数组
for(int i=0;i<ch.length;i++)
print("ch["+i+"]="+ch[i]);
int t = 456;
String st = String.valueOf(t);//将基本数据类型int转换成字符串
print(st);//456
}
public static void method_HuoQu(){//获取字符串的方法
String str = "abcdefabact";
//长度
print(str.length());//11
//根据索引获取字符
print(str.charAt(2));//c 如果输入的值超过字符串长度,会出现字符串越界异常StringInedxOutBoundsException
//根据字符串获取索引
print(str.indexOf('b',5));//7 从第5个字符开始往后找b的索引
//反向索引一个字符串出现的位置
print(str.lastIndexOf('b',5));
}
public static void method_PanDuan(){//1 判断字符串的方法
String str = "abcdefabact";
print(str.contains("ac"));//true 判断字符串中是否存在子串"ac"
print(str.isEmpty());//false 判断字符串长度是否为0
print(str.startsWith("acb"));//false 判断字符串是否以"acb"开头
print(str.endsWith("act"));//true 判断字符串是否以"act"结尾
print(str.equals("sdf"));//false 判断字符串内容是否相同
print(str.equalsIgnoreCase("ABCdefabact"));//true
}
public static void main(String[] args) {
// method_HuoQu();
// method_PanDuan();
// method_ZhuanHuan();
// method_TiHuan();
// method_QieGe();
// method_ZiChuan();
method_7();
}
public static void print(Object obj){
System.out.println(obj);
}
}
String中的方法使用练习
/*
* 1,模拟一个trim方法,去除字符串两端的空格。
* 思路:
* 1,判断字符串第一个位置是否为空格,如果是则继续向下判断,直到不是空格为止。
* 结尾处判断也是如此。
* 2,当开始和结尾都判断到不是空格时,就是要获取的字符串。
*/
public class Demo {
public static String lianXi_1(String str) {
int start = 0, end = str.length() - 1;
while (start <= end && str.charAt(start) == ' ')
start++;
while (start <= end && str.charAt(end) == ' ')
end--;
return str.substring(start, end + 1);
}
public static void main(String[] args) {
print(lianXi_1(" abcd ef fg "));
}
public static void print(String s) {
System.out.println(s);
}
}
/*
*2,将一个字符串进项反转。将字符串中指定的部分进行反转。"abcdefg";abfedcg
*思路:
* 1,曾经学习对数组的元素进行反转。
* 2,将字符串变成数组,对数组反转。
* 3,将反转后的数组变成字符串。
* 4,只要将反转的部分的开始和结束位置作为参数传递即可。
*/
public class Demo {
// 将一个字符串进项反转
public static String lianXi_2(String str) {
return lianXi_2(str, 0, str.length());
}
// 将字符串中指定的部分进行反转
public static String lianXi_2(String str, int start, int end) {
char[] chs = str.toCharArray();
reverse(chs, start, end);
return String.valueOf(chs);
}
private static void reverse(char[] chs, int x, int y) {
for (int start = x, end = y - 1; start < end; start++, end--)
swap(chs, start, end);
}
private static void swap(char[] chs, int start, int end) {
char temp = chs[start];
chs[start] = chs[end];
chs[end] = temp;
}
private static void print(String s){
System.out.println(s);
}
public static void main(String[] args) {
print(lianXi_2("abcd"));
print(lianXi_2("abcd", 0, 3));
}
}
/*
* 3,获取一个字符串在另一个字符串中出现的次数。
* "abkkcdkkefkkskk"
* 思路:
* 1,定义个计数器
* 2,获取kk第一次出现位置。
* 3,从第一次出现位置后剩余的字符串中继续获取kk出现的位置。
* 每获取一次就计数一次。
* 4,当获取不到时计数完成
*/
//方式一
public class Demo {
public static int lianXi_3(String s1, String s2) {
int count= 0;//定义一个计数器
int index = 0;
while((index=s1.indexOf(s2))!=-1){//查找s2在s1中第一次出现的位置,如果不存在则跳出循环
count++; //查找到了计数器自动加一
System.out.println(s1);
s1 = s1.substring(index+s2.length(),s1.length());//从查找到的位置开始,获取该位置后边的字符串
}
return count;
}
public static void main(String[] args) {
System.out.println(lianXi_3("abkkcdkkefkkskkkk","kk"));
}
}
//方式二
public class Demo {
public static int lianXi_3(String s1, String s2) {
int count = 0;
int index = 0;
while ((index = s1.indexOf(s2, index)) != -1) {// 如果存在元素,则遍历
count++;// 存在元素,则计数器加一
index = index + s2.length();// 改变角标的位置
}
return count;
}
public static void main(String[] args) {
String s1 = "kkkabkkcdkkefkkskkk";
String s2 = "kk";
System.out.println(lianXi_3(s1, s2));
}
}
/*
* 4,获取两个字符串中最大相同子串。第一个动作:将短的那个串进行长度依次递减的子串打印。
* "abcwerthelloyyuiodef"
* "cvhellobnm"
* 思路:
* 1,将短的那个子串按照长度递减的方式获取到。
* 2,将获取到的子串去长串中判断是否包含,如果包含,已经找到。
*/
public class Demo {
public static String lianXi_4(String s1, String s2) {
if (s1.length() < s2.length()) {//如果s1的长度小于s2,则交换。既:s1为长串,s2为短串
String temp = s2;
s2 = s1;
s1 = temp;
}
for (int i = 0; i < s2.length(); i++) {
//j表示s2起始坐标,k表示s2末尾的坐标,如果比较的短子串不在长串中,那么j和k都向右移动一位,然后继续比较
for (int j = 0, k = s2.length() - i; k <= s2.length(); j++, k++) {
String temp = s2.substring(j,k);
//System.out.println(temp);
if(s1.contains(temp))
return s2.substring(j,k);
}
}
return null;
}
public static void main(String[] args) {
System.out.println(lianXi_4("cvhellobnm", "abcwerthelloyyuiodef"));
}
}
StringBuffer类
StringBuffer是字符串缓冲区。
是一个容器。
特点:
1,长度是可变化的。
2,可以直接操作多个数据类型。
3,最终会通过toStrong变成字符串。
CURD
C:create创建 U:update更新 R:read读取 D:delete删除
1,存储
StringBuffer append():将指定数据作为参数添加到已有数据结尾处。
StringBuffer insert(index,数据):可以将数据插入到index位置
2,删除。
StringBuffer delete(start,end):删除缓冲区中的数据,包含start,不包含end
StringBuffer deleteCharAt(index):删除指定位置的字符
3,获取。
char charAt(index):获取指定位置的字符
int indexOf(String str):获取某个字符串第一次出现的位置
int lastIndexOf(String str):反向获取某个字符串第一次出现的位置
int length():获取字符串的长度
String subString(start,end):获取某个字符串的子串,从start开始到end,不包含end
4,修改
StringBuffer replace(start,end,string):将start到end的字符串改为string,记住,不包含end/
void setCharAt(int index,char ch):将index位置的字符修改成ch
5,反转
StringBuffer reverse():将指定的字符串取反
6,将缓冲区中指定数据存储到指定字符数组中
void getChars(int srcstart,int srcend,char[] ch,int dststart):将缓冲区中的字符串
从srcstart到srcend中的数据存储到ch中,ch中的起始位置为dststart
StringBuffer什么时候使用:数据类型不确定,最终都要变成字符串,数据个数不确定的时候。
JDK1.5 版本之后出现了StringBuilder
StringBuffer是线程同步
StringBuilder是线程不同步
注意: 以后开发,建议使用StringBuilder
升级三个因素:
1,提高效率
2,提高安全性
3,简化书写
代码示例:
public class Demo {
public static void haha(){
int[] a = {1,2,3,4};
}
public static void main(String[] args) {
// function_add();
// function_delete();
function_update();
StringBuffer sb = new StringBuffer("abcdefg");// 创建缓冲区的时候就初始化为abcdefg
char[] ch = new char[6];
sb.getChars(1, 4, ch, 2);//将1到4中的数据插入ch中的2位置
for (int i = 0; i < ch.length; i++)
print("ch[" + i + "]=" + ch[i]);//结果: _ _ bcd_ 下划线代表没有数值
}
public static void function_update() {//修改
StringBuffer sb = new StringBuffer("abcd");
sb.replace(1, 3, "java");
print(sb.toString());//结果ajavad
StringBuffer sb1 = new StringBuffer("abcd");
sb1.setCharAt(2, 'd');
print(sb1.toString());//结果abdd
}
public static void function_delete() {//删除
StringBuffer sb = new StringBuffer("abcdef");
sb.delete(1, 3);
print(sb.toString());// 结果adef
//清空sb中的数据
sb.delete(0,sb.length());
print(sb.toString());
StringBuffer sb1 = new StringBuffer("abcdef");
sb1.deleteCharAt(1);
print(sb1.toString());// 结果acdef
}
public static void function_add() {//添加
StringBuffer sb = new StringBuffer();
sb.append("abc").append(true).append(123);
print(sb.toString());// 结果:abctrue123
sb.insert(2, "haha");
print(sb.toString());// 结果:abhahactrue123
}
public static void print(String s) {
System.out.println(s);
}
}
基本数据类型对象包装类
byte Byte
short Short
int Integer
long Long
double Double
char Character
boolean Boolean
基本数据类型对象包装类的最常见作用,就是用于基本数据类型和字符串类型之间做转换
1,基本数据类型转成字符串
基本数据类型+”“;
String.valueOf(基本数据类型);
基本数据类型.toString(基本数据类型);
如: String str = Integer.toString(34);//将34变成字符串
2,字符串转成基本数据类型
xxx a = Xxx.parseXxx(String);
int a = Integer.parseInt(“123”);//将字符串123转成int类型
double d = Double.parseDouble(“123.4”);//将字符串123.4转成double类型
boolean b = Boolean.parseBoolean(“true”);//将字符串true转成boolean类型
Integer i = new Integer(“123456”);
int num = i.intValue();//将字符串123456转成int类型,此方法是非静态的,必须通过对象调用
3,十进制转成其他进制
String str = Integer.toBinaryString(6);//将6转成二进制
String str = Integer.toHexString(60);//将60转成十六进制
String str = Integer.toOctalString(9);//将9转成八进制
int i = Integer.toString(6, 2);//将6转成二进制
int i = Integer.toString(6,4);//将6转成四进制
4,其他进制转十进制
int i = Integer.parseInt(“3c”,16);//将十六进制的3c转成十进制
int i = Integer.parseInt(“110”,2);//将二进制的110转成十进制
int i = Integer.parseInt(“110”,10);//将十进制的110转成十进制
代码示例:
public class Demo {
public static void main(String[] args) {
print(Integer.MAX_VALUE+"");//结果2147483647,此方法输出int类型的最大值
print(Integer.toBinaryString(6));//结果110,将6转成二进制
print(Integer.toHexString(60));//结果 3c,将60转成十六进制
}
public static void print(String s){
System.out.println(s);
}
}
/*
* JDK1.5 版本以后出现的新特性。
*/
public class Demo {
public static void main(String[] args) {
Integer a = new Integer(127);
Integer b = new Integer(127);
print(a==b);//false //不管是不是在-128~127范围 a和b都是不同对象
print(a.equals(b));//true
Integer c = new Integer(128);
Integer d = new Integer(128);
print(c==d);//false //不管是不是在-128~127范围 c和d都是不同对象
print(c.equals(d));//true
Integer x = 127;
Integer y = 127;//JDK1.5 以后,自动装箱,如果装箱是byte范围内(-128~127),如果该数值已经存在,则不会开辟新的空间
print(x == y);//true 注意:x和y指向了同一个对象,因为x和y在-128~127之间
print(x.equals(y));//false
Integer z = 128;
Integer k = 128;//因为128超过了byte范围,所以新开辟了一个空间
print(z == k);//false 注意:z和k是不同对象,因为z和k大于 byte范围(-128~127)
print(z.equals(k));//false
Integer i1 = 4;
Integer i2 = i1 + 2;// i1进行自动拆箱,变成int类型,和2进行加法运算。再将和进行自动装箱赋值给i2。 i1自动拆箱的方式是 i1.intValue();
}
public static void print(Object o){
System.out.println(o);
}
}
Math类
代码示例:
/*
* Math类和Random类
*
* 面试题
*/
import java.text.SimpleDateFormat;
import java.util.*;
public class Demo {
public static void main(String[] args){
// function1();
function2();
}
public static void function2(){
for(int i=0;i<10;i++){
int x = (int)(Math.random()*10+1);
System.out.print(x+" ");//结果:1~10之间的随机数
}
System.out.println();
Random r = new Random();
for(int i=0;i<10;i++){
int x = r.nextInt(10)+1;
System.out.print(x+" ");//结果:1~10之间的随机数
}
System.out.println();
}
public static void function1(){
double d1 = Math.ceil(16.34);//ceil返回大于指定数据的最小整数
double d2 = Math.floor(16.34);//floor返回小于指定数据的最大整数
print("d1="+d1);//17.0
print("d2="+d2);//12.0
double d3 = Math.pow(2, 3);//2的3次幂
print("d3="+d3);//d3=8.0
long long1 = Math.round(12.51);//四舍五入
long long2 = Math.round(12.49);//四舍五入
print("long1="+long1);//long1=13
print("long2="+long2);//long2=12
}
public static void print(Object obj){
System.out.println(obj);
}
}
/*
* 练习:
* 给定一个小数,保留该小数的后两位。
*/
import java.util.*;
public class Demo {
public static void main(String[] args){
double d = function(123.5646);
print(d);
}
public static double function(double d){
double dou = (double)Math.round(d * 100)/100; //将给定的数123.5646*100=12356.46。然后四舍五入得12356。12356/100=123.56
return dou;
}
public static void print(Object obj){
System.out.println(obj);
}
}
Calendar类
代码示例:
/*
* Calendar对象(日历对象)
*/
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Demo {
public static void main(String[] args){
// getYear();
// calendarDemo1();
// calendarDemo2();
// calendarDemo3();
calendarDemo4();
}
public static void calendarDemo4(){
Calendar c = Calendar.getInstance();
//根据日历的规则,为给定的日历字段添加或减去指定的时间量。
// c.add(Calendar.YEAR, 3);//在原有的年份上+3
// c.add(Calendar.MONTH, 3);//在原有的月份上+3
c.add(Calendar.MONTH, -5);//在原有的月份上-5
String[] month = {"一月","二月","三月","四月",
"五月","六月","七月","八月",
"九月","十月","十一月","十二月"};
String[] week = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
int y = c.get(Calendar.YEAR);//返回给定日历字段的值。日历字段为YEAR。具体查看java.util包中的Calendar类
int m = c.get(Calendar.MONTH);//返回给定日历字段的值。日历字段为MONTH,MONTH从0开始。具体查看java.util包中的Calendar类
int d = c.get(Calendar.DAY_OF_MONTH);//DAY_OF_MONTH 为月中的某天
int w = c.get(Calendar.DAY_OF_WEEK)-1;
print(y+"."+month[m]+"."+d+"日"+"."+week[w]);//结果:2014.十二月.21日.星期日。 当天的日历为2015.五月.21日.星期四
}
public static void calendarDemo3(){
Calendar c = Calendar.getInstance();
c.set(2020, 1, 1);//设置某年某月
String[] month = {"一月","二月","三月","四月",
"五月","六月","七月","八月",
"九月","十月","十一月","十二月"};
String[] week = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
int y = c.get(Calendar.YEAR);//返回给定日历字段的值。日历字段为YEAR。具体查看java.util包中的Calendar类
int m = c.get(Calendar.MONTH);//返回给定日历字段的值。日历字段为MONTH,MONTH从0开始。具体查看java.util包中的Calendar类
int d = c.get(Calendar.DAY_OF_MONTH);//DAY_OF_MONTH 为月中的某天
int w = c.get(Calendar.DAY_OF_WEEK)-1;
print(y+"."+month[m]+"."+d+"日"+"."+week[w]);//2020.二月.1日.星期六
}
public static void calendarDemo2(){
Calendar c = Calendar.getInstance();//使用默认时区和语言环境获得一个日历。
String[] month = {"一月","二月","三月","四月",
"五月","六月","七月","八月",
"九月","十月","十一月","十二月"};
String[] week = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
int y = c.get(Calendar.YEAR);//返回给定日历字段的值。日历字段为YEAR。具体查看java.util包中的Calendar类
int m = c.get(Calendar.MONTH);//返回给定日历字段的值。日历字段为MONTH,MONTH从0开始。具体查看java.util包中的Calendar类
int d = c.get(Calendar.DAY_OF_MONTH);//DAY_OF_MONTH 为月中的某天
int w = c.get(Calendar.DAY_OF_WEEK)-1;
print(y+"."+month[m]+"."+d+"日"+"."+week[w]);//2015.五月.21日.星期四
}
//Calendar类演示
public static void calendarDemo1(){
Calendar c = Calendar.getInstance();//使用默认时区和语言环境获得一个日历。
int year = c.get(Calendar.YEAR);//返回给定日历字段的值。日历字段为YEAR。具体查看java.util包中的Calendar类
int month = c.get(Calendar.MONTH)+1;//返回给定日历字段的值。日历字段为MONTH,MONTH从0开始。具体查看java.util包中的Calendar类
int day = c.get(Calendar.DAY_OF_MONTH);//DAY_OF_MONTH 为月中的某天
print(year+"年"+month+"月"+day+"日");//2015年5月21日
}
public static void getYear() {
// 获取某年
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
Date d = new Date();
String year = sdf.format(d);
print("year=" + year);//year=2015
}
public static void print(Object obj) {
System.out.println(obj);
}
}
Date类
/*
* Date对象(日期对象)
* SimpleDateFormat对象 (格式化Date对象的对象)
*/
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Demo {
public static void main(String[] args){
Date d = new Date();
print(d);//Thu May 21 09:51:12 GMT+08:00 2015。打印时间看不懂,希望有些格式
//将模式封装到SimpleDateFormat对象中。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 E hh:mm:ss");//具体查看API文档的java.text包
//调用format方法让模式格式化指定的Date对象。
String time = sdf.format(d);
print(time);//2015年05月21日 星期四 10:05:31
//获取当前的毫秒数
SimpleDateFormat sdf2 = new SimpleDateFormat("S");//具体查看API文档的java.text包
String time1 = sdf2.format(d);
print(time1);//427
//获取从1970年到现在的毫秒数
long l = System.currentTimeMillis();
print(l);//1432173931450
}
public static void print(Object obj) {
System.out.println(obj);
}
}