Java字符串

一,装箱和拆箱

低级别转为高级别,可以实现自动装和拆箱,反之是不行的

public class Test{
	public static void main(){
			int a=10;
			Integer test1 = new Integer(i); // 基本类型  ——→ 封装类
			int a = test1.IntValue(); // 封装类 ——→ 基本类型
			Integer test2 = a; //自动装箱
			a = test2 // 自动拆箱
			
	    //int的最大值
        System.out.println(Integer.MAX_VALUE);
        //int的最小值      
        System.out.println(Integer.MIN_VALUE);
        
	}
}

二、数字转字符串


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();
        
    }
}

三、字符串转数字

调用类型封装类的静态静态方法 parseInt(String)

 
public class TestNumber {
 
    public static void main(String[] args) {

    	String str = "999";
    	
    	int i= Integer.parseInt(str);
    	
    	System.out.println(i);
        
    }
}

四、数学方法:

(1)四舍五入 Math.round()

(2)随机数 Math.random()

(3)开方Math.sqrt、平方Math.pow

(4)Math.PI 、 Math.E


 
public class TestNumber {
 
    public static void main(String[] args) {
    	float f1 = 5.4f;
    	float f2 = 5.5f;
    	四舍五入
    	System.out.println(Math.round(f1));
    	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));
    	次方(24次方)
    	System.out.println(Math.pow(2,4));
    	
    	π
    	System.out.println(Math.PI);
    	
    	自然常数
    	System.out.println(Math.E);
    }
}

五、格式化输出 %n

为了使得同一个java程序的换行符在所有的操作系统中都有一样的表现,使用%n,就可以做到平台无关的换行

package digit;
 
public class TestNumber {
 
    public static void main(String[] args) {

    	String name ="盖伦";
    	int kill = 8;
    	String title="超神";
    	
    	//直接使用+进行字符串连接,编码感觉会比较繁琐,并且维护性差,易读性差
    	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);
    	
    }
}

六、字符Character . 静态方法

(1)isLetter

(2)isDigit

(3)isWhitespace

(4)isLowerCase 和 isUpperCase

package character;

public class TestChar {

	public static void main(String[] args) {
		
		System.out.println(Character.isLetter('a'));//判断是否为字母
		System.out.println(Character.isDigit('a')); //判断是否为数字
		System.out.println(Character.isWhitespace(' ')); //是否是空白
		System.out.println(Character.isUpperCase('a')); //是否是大写
		System.out.println(Character.isLowerCase('a')); //是否是小写
		
		System.out.println(Character.toUpperCase('a')); //转换为大写
		System.out.println(Character.toLowerCase('A')); //转换为小写

		//String a = 'a'; 不能够直接把一个字符转换成字符串
		String a2 = Character.toString('a'); //转换为字符串
		
	}
}

七、字符串转字符数组 toCharArray

package digit;
 
import java.util.Scanner;
 
/**
 *  通过Scanner从控制台读取字符串,然后把字符串转换为字符数组
    参考的转换方式:
      
    String str = "abc123";
    char[] cs = str.toCharArray(); 
      
    转换为字符数组后,筛选出控制台读取到的字符串中的大写字母和数字,并打印出来
 *
 */
public class TestCharacter {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);     //调用控制台的输入流
        System.out.println("请输入字符串:");
        String str = s.nextLine();              //输入数据为字符串
         
        System.out.println("其中大写字母和数字有:");
        char[] cs = str.toCharArray();          //字符串转字符数组
        for (int i = 0; i < cs.length; i++) {    //遍历数组长度
            char c = cs[i];                     //声明字符变量接收每一个数组
            if (Character.isUpperCase(c) || Character.isDigit(c)) {
                System.out.print(c+" ");        //输出大写字母和数字
            }
        }
    }
}

八、字符串是一个类,所以我们见到的字符串都是对象

字符串即字符的组合,在Java中,字符串是一个类,所以我们见到的字符串都是对象
常见创建字符串手段:

  1. 每当有一个字面值出现的时候,虚拟机就会创建一个字符串

  2. 调用String的构造方法创建一个字符串对象:String s1 = new String(s2)

  3. 通过+加号进行字符串拼接也会创建新的字符串对象:String s3 = s1 + s2 ;

  4. 通过字符数组创建字符串

  5. 封装类.toString()可以转字符串

    String teemo = new String(“提莫”); //创建了两个字符串对象,即teemo 和 “提莫” ,两个字符串对象

package character;

public class TestString {

	public static void main(String[] args) {
		String garen ="盖伦"; //字面值,虚拟机碰到字面值就会创建一个字符串对象
		
		String teemo = new String("提莫"); //创建了两个字符串对象
		
		char[] cs = new char[]{'崔','斯','特'};
		
		String hero = new String(cs);//  通过字符数组创建一个字符串对象
		
		String hero3 = garen + teemo;//  通过+加号进行字符串拼接
	}
}

String 被修饰为final,所以是不能被继承的
immutable 是指不可改变的,相当于字符串常量,直接字面值创建的字符串对象就是;
string s.length方法返回当前字符串的长度
可以有长度为0的字符串,即空字符串

九、 字符串(查,换,改)常用方法

(1)charAt (int index)获取指定下标字符字符

String sentence = "你好啊啊啊啊啊";
         
char c = sentence.charAt(0);

(2)toCharArray() 字符串转字符数组

 String str = "字符串转数组";            
 char[] cs = str.toCharArray();       

(3)subString (起始位置,终止位置)截取子字符串

package character;
   
public class TestString {
   
    public static void main(String[] args) {
  
    	String sentence = "盖伦,在进行了连续8次击杀后,获得了 超神 的称号";
    	
    	//截取从第3+1个开始的字符串 (基0)
    	String subString1 = sentence.substring(3); 
    	
    	System.out.println(subString1);
    	
    	//截取从第3个开始的字符串 (基0)
    	//到5-1的位置的字符串 
    	//左闭右开:3+1 到 5(也就是 4 到 5 的字符)
    	String subString2 = sentence.substring(3,5); 
    	
    	System.out.println(subString2);
    	
    }
}

在这里插入图片描述

(4)split 按字符或字符串分隔

package character;
   
public class TestString {
   
    public static void main(String[] args) {
  
    	String sentence = "盖伦,在进行了连续8次击杀后,获得了 超神 的称号";
    	
    	//根据,进行分割,得到3个子字符串
    	String subSentences[] = sentence.split(",");
    	for (String sub : subSentences) {
			System.out.println(sub);
		}

trim 去掉首尾空格

package character;
   
public class TestString {
   
    public static void main(String[] args) {
  
    	String sentence = "        盖伦,在进行了连续8次击杀后,获得了 超神 的称号      ";
    
    	//去掉首尾空格
    	System.out.println(sentence.trim());
    }
}

(5)toLowerCase 和toUpperCase 变大小写

//全部变成小写
 System.out.println(sentence.toLowerCase());
//全部变成大写
System.out.println(sentence.toUpperCase());

(6)返回出现位置:indexOf、lastIndexOf 、contains

indexOf 返回字符或者子字符串出现的位置
lastIndexOf 最后一次出现的位置
contains 是否包含子字符串

package character;
    
public class TestString {
    
    public static void main(String[] args) {
   
        String sentence = "盖伦,在进行了连续8次击杀后,获得了超神 的称号";
 
        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("击杀")); //是否包含字符串"击杀"
         
    }
}

(7)替换:replaceAll 和 replaceFirst

replaceAll 替换所有的
replaceFirst 只替换第一个

package character;
   
public class TestString {
   
    public static void main(String[] args) {
  
    	String sentence = "盖伦,在进行了连续8次击杀后,获得了超神 的称号";

    	String temp = sentence.replaceAll("击杀", "被击杀"); //替换所有的
    	
    	temp = temp.replaceAll("超神", "超鬼");
    	
    	System.out.println(temp);
    	
    	temp = sentence.replaceFirst(",","");//只替换第一个
    	
    	System.out.println(temp);
    	
    }
}

(8)练习:

  1. 把每个单词的首字母变成大写
  2. 统计多少个p的字母
  3. 间隔大小写
  4. 把 lengendary 最后一个字母变大写
  5. 把最后一个two单词首字母大写
public static void main(String[] args) {
        //把每个单词的首字母变成大写
        String sentence="let there be light";
        char c ;
        String []sen=sentence.split(" ");//分隔成字符串数组
        for(int i=0;i<sen.length;i++) {
            c=sen[i].charAt(0);//获取首字母
            c=Character.toUpperCase(c);//转化为大写
            sen[i]=sen[i].replace(sen[i].toCharArray()[0], c);//替换第一个字母
        }
        System.out.println(sentence);
        for(String s:sen) {
            System.out.print(s+" ");
        }
         
        System.out.println("\n----------------------");
        //统计多少个p的字母
        String sentence1="peter piper picked a peck of pickled peppers";
        sentence1=sentence1.replaceAll(" ", "");
        int count=0;
        for(int i=0;i<sentence1.length();i++) {
            char s=sentence1.charAt(i);//获取每个字母
            String str=s+"";
            System.out.print(s);
            if("p".equals(str)) {
                count++;
            }
        }
        System.out.printf("\n一共有%d个p字母",count);
         
        System.out.println("\n--------------------");
        //间隔大小写
        String str1="lengendary";
        String str2="";
        char []st=str1.toCharArray();
        System.out.println(str1);
        for(int i=0;i<st.length;i++) {
            if(i%2==0) {//偶数就转换为大写
                st[i]=Character.toUpperCase(st[i]);
            }
            str2+=Character.toString(st[i]);
        }
        System.out.println(str2);
         
        System.out.println("\n--------------------");
        //把 lengendary 最后一个字母变大写
        String str3="lengendary";
        String str4="";
        char [] st1=str3.toCharArray();
        System.out.println(str3);
        for(int i=0;i<st1.length;i++) {
            if(i==st1.length-1) {
                st1[i]=Character.toUpperCase(st1[i]);
            }
            str4+=Character.toString(st1[i]);
        }
        System.out.println(str4);
         
        System.out.println("\n--------------------");
        //Nature has given us that two ears, two eyes, and but one tongue, to the end that we should hear and see more than we speak
        //把最后一个two单词首字母大写
        String sentence3="Nature has given us that two ears, two eyes, and but one tongue, to the end that we should hear and see more than we speak";
    //  System.out.println(sentence3.lastIndexOf("two"));   //获取最后一个two的位置
        System.out.println(sentence3);
        String sentence4="";
        char c1;
        for(int i=0;i<sentence3.length();i++) {
            c1=sentence3.charAt(sentence3.lastIndexOf("two"));
            if(i==sentence3.lastIndexOf("two")) {
                c1=Character.toUpperCase(c1);
                sentence4+=Character.toString(c1);
            }else {
                c1=sentence3.charAt(i);
                sentence4+=Character.toString(c1);
            }
        }
        System.out.println(sentence4);
    }

十、 字符串比较

1. 对象比较

(1)此时str1 和 str 2 是不一样的

		String str1 = "the light";
		
		String str2 = new String(str1);
		    //==用于判断是否是同一个字符串对象
        System.out.println( str1  ==  str2)//false

(2)一般说来,编译器每碰到一个字符串的字面值,就会创建一个新的对象
所以先创建了一个新的字符串"the light"
但接下一行,编译器发现已经存在现成的"the light",那么就直接拿来使用,而没有进行重复创建

        String str1 = "the light";
        String str3 = "the light";
        System.out.println( str1  ==  str3);

2. 内容比较 equals、 startWith/endsWith

(1)使用equals进行字符串内容的比较,必须大小写一致
(2)equalsIgnoreCase,忽略大小写判断内容是否一致

package character;
 
public class TestString {
 
    public static void main(String[] args) {
 
        String str1 = "the light";
         
        String str2 = new String(str1);
        
        String str3 = str1.toUpperCase();

        //==用于判断是否是同一个字符串对象
        System.out.println( str1  ==  str2);//false
        
        System.out.println(str1.equals(str2));//完全一样返回true
        
        System.out.println(str1.equals(str3));//大小写不一样,返回false
        System.out.println(str1.equalsIgnoreCase(str3));//忽略大小写的比较,返回true
        
    }
 
}

(3)startsWith //以…开始、endsWith //以…结束

package character;
 
public class TestString {
 
    public static void main(String[] args) {
        String str1 = "the light";
        
        String start = "the";
        String end = "Ight";
        
        System.out.println(str1.startsWith(start));//以...开始
        System.out.println(str1.endsWith(end));//以...结束
         
    }
 

(4)练习:统计重复字符串

创建一个长度是100的字符串数组
使用长度是2的随机字符填充该字符串数组
统计这个字符串数组里重复的字符串有多少种


public class TestString {
    //产生随机字符串方法
    public static String randomString(int length) {
        String result = "";
        for (int j = 0; j < length; j++) {
            while (true) {
                char c = (char) (Math.random() * ('z' - '0' + 1) + '0');
                if (Character.isLetterOrDigit(c)) {
                    result += c;
                    break;
                }
            }
        }
        return result;
    }
 
    public static void main(String[] args) {
        String[] s = new String[100];
         
        //生成随机字符串
        for (int i = 0; i < s.length; i++) {
            s[i] = randomString(2);
        }
         
        for (int i =0; i<s.length; i++) {
            System.out.print(s[i] + " ");
            if(i%20 == 19)
                System.out.println("");
        }
         
        //统计重复字符串
        int count = 0;
        boolean flag = false;
        String result = "";
        String[] ss = s; //为了保留原字符串数组s,所以新创建了ss
        for (int i = 0; i < ss.length - 1; i++)
            for (int j = i + 1; j < ss.length; j++) {
                if (ss[i] == " ")
                    break;
                if (ss[i].equalsIgnoreCase(ss[j])) {
                    ss[j] = " ";
                    flag = true;
                }
                if (flag) {
                    result += ss[i] + " ";
                    count++;
                    flag = false;
                }
            }
        System.out.println("\n重复的字符串共有" + count +"种,分别是:\n"+result);
    }
 
}

★★★十一、stringBuffer(增、删、插、反转)

(1)为什么StringBuffer可以变长?

和String内部是一个字符数组一样,StringBuffer也维护了一个字符数组。 但是,这个字符数组,留有冗余长度
比如说new StringBuffer(“the”),其内部的字符数组的长度,是19,而不是3,这样调用插入和追加,在现成的数组的基础上就可以完成了。
如果追加的长度超过了19,就会分配一个新的数组,长度比原来多一些,把原来的数据复制到新的数组中,看上去 数组长度就变长了 参考MyStringBuffer
length: “the”的长度 3
capacity: 分配的总空间 19

package character;
 
public class TestString {
 
    public static void main(String[] args) {
        String str1 = "let there ";

        StringBuffer sb = new StringBuffer(str1); //根据str1创建一个StringBuffer对象
        sb.append("be light"); //在最后追加
        
        System.out.println(sb);
        
        sb.delete(4, 10);//删除4-10之间的字符
        
        System.out.println(sb);
        
        sb.insert(4, "there ");//在4这个位置插入 there
        
        System.out.println(sb);
        
        sb.reverse(); //反转
        
        System.out.println(sb);

    }
 
}
package character;
 
public class TestString {
 
    public static void main(String[] args) {
        String str1 = "the";

        StringBuffer sb = new StringBuffer(str1);
        
        System.out.println(sb.length()); //内容长度
        
        System.out.println(sb.capacity());//总空间
 
    }
 
}

(2)String与StringBuffer的性能区别?

生成10位长度的随机字符串
然后,先使用String的+,连接10000个随机字符串,计算消耗的时间
然后,再使用StringBuffer连接10000个随机字符串,计算消耗的时间
有个视屏待看

十二、讨论

(1)怎么将字符数组转为整型数字

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值