黑马程序员----------java基础API之String类的介绍和使用

                                    ----------------------android培训java培训、期待与您交流! ----------------------

因为在java中String类应用非常广泛,所以单独总结一下String类的常用方法以及注意事项。

字符串(String

常用字符串的操作:

1、初始化一个新字符对象new String();

package HomeWork2;
/*
 * 需求: 
 * 	键盘录入一个字符串,遍历该字符串
 * */
import java.util.Scanner;

public class PrintString {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
//		从键盘录入一个字符串
		String str = sc.nextLine();
//		定义一个记录该字符串长度的变量
		int length = str.length();
		for (int i = 0; i < length; i++) {
			System.out.println(str.charAt(i));
		}
	}
}


2、charAt(int index);返回指定索引处的char值;


3、compareTo(String a,String b);按活字典的顺序比较两个字符串;

package cn.itheima;

/*
 * 按照字典顺序比较:
 * 		public int compareTo(String anotherString)
 * 		public int compareToIgnoreCase(String str)
 */
public class StringDemo3 {
	public static void main(String[] args) {
		String s = "hello";

		String s1 = "abc";
		String s2 = "hello";
		String s3 = "kimi";
		String s4 = "Hello";

		System.out.println(s.compareTo(s1));
		System.out.println(s.compareTo(s2));
		System.out.println(s.compareTo(s3));
		System.out.println(s.compareTo(s4));
		
		System.out.println(s.compareToIgnoreCase(s4));
	}
}



4、concat(String s);将指定字符串连接到此字符串结尾;


5、contains(char[] s);判断字符串中是否包含此字符串。


6、copyValueOf(char[] s);将字符数组转换成String 字符串;


7、endsWith(String s);判断此字符串是否以指定的后缀结束;


8、getBytes();将String字符串转换成字节(byte)数组;


9、indexOf(String s)返回此字符串在指定字符串中第一次出现的索引位置


10、isEmpty()判断该字符串是否是空值当且仅当length()0时返回true


11、lastIndexOf()返回指定字符串在此字符串中最后一次出现的索引值


12、Length()返回字符串的长度


13、Replace(char oldChar,char newChar)返回一个新的字符串,

package cn.itheima;

/*
 * 替换功能:
 * public String replace(char oldChar,char newChar)
 * public String replace(String oldString,String newString)
 */
public class StringDemo {
	public static void main(String[] args) {
		String s = "helloworld";

		// public String replace(char oldChar,char newChar)
		String result = s.replace('o', 'a');
		System.out.println(result);

		// public String replace(String oldString,String newString)
		String result2 = s.replace("owo", "ak47");
		System.out.println(result2);
	}
}


它是通过用newChar 替换此字符串中出现的所有oldChar


14、split(String s)用于分隔字符串


15、startsWith(String s)判断此字符串是否以指定的前缀开始。


16、Substring(int beginIndex,int endIndex)

返回一个新的字符串,它是此字符串的一个子字符串。


17、toCharArray()将此字符串转换为一个新的字符数组;


18、toLowerCase()将此字符串中所有的字符都转换为小写;


19、toUpperCase()将此字符串中所有的字符都转换为大写;


20、Trim()删除字符串中的前后空格;

package cn.itheima;

/*
 * 场景:
 *         用户名:" ad min "
 *
 * 作业:假如我们要自己实现一个去除字符串前后空格的功能。怎么做。
 */
public class StringDemo2 {
    public static void main(String[] args) {
        // public String trim()
        String s = "   a dmin   ";

        String result = s.trim();

        System.out.println("---" + s + "----");
        System.out.println("---" + result + "----");
    }
}

package cn.itcast_01;

/*
 * 描述一下:
 * 		假如我一个字符串:
 * 			"  a dmin  "
 * 
 * 		A:定义字符串
 * 		B:定义一个起始索引,记录查找到第一个不是空格的位置。
 * 		C:定义一个结束索引,记录查找到从后往前第一个不是空格的位置。
 * 		D:截取。
 */
public class StringTest {
	public static void main(String[] args) {
		// 定义字符串
		String s = " a dmin  ";

		String result = myTrim(s);
		System.out.println("---" + result + "---");
	}

	/*
	 * 明确返回值类型:String 没有前后空格的 明确参数列表:String 带前后空格的
	 */
	public static String myTrim(String str) {
		// 定义一个起始索引,记录查找到第一个不是空格的位置。
		int start = 0;
		// 定义一个结束索引,记录查找到从后往前第一个不是空格的位置。
		int end = str.length() - 1;

		// 记录第一个不是空格的索引
		while (String.valueOf(str.charAt(start)).equals(" ") && start <= end) {
			start++;
		}

		// 记录最后一个不是空格的索引
		while (String.valueOf(str.charAt(end)).equals(" ") && start <= end) {
			end--;
		}

		// 截取
		String result = str.substring(start, end + 1);

		// 返回
		return result;
	}
}




21、valueOf(char c)将char转换成字符串


StringBuffer :字符串缓冲区

CRUD:增删改查

Create read update delete

1、增加插入

StringBuffer insert(index,data):可以将数据插入到指定index位置


2、删除。

StringBuffer delete(start ,end):删除缓冲区中的数据,包含start,但不包含end;

StringBuffer deleteCharAt( int index):删除指定位置的字符;


3、修改:

StringBuffer replace(int start,int end);

Void setCharAt(int index,char chr);


4、查询获取:

Char charAt(int index)


int indexOf(String str)


int lastIndexOf(String str)


Int length();


String subString(int start,int end);


5、反转:


StringBuffer reverse();


StringBuffer是线程同步


StringBuilder是线程不同步


升级三个因素:提高效率、简化书写、提高安全性

package cn.itcast_06;

/*
 * 需求:
 * 		我有一个字符串:"egabdcf"
 * 		请想办法,我要最终看到一个字符串:"abcdefg"
 * 
 * 分析:
 * 		A:定义一个字符串。
 * 		B:把字符串转换成字符数组。
 * 		C:对数组排序。模仿刚才的代码,把int改为char即可。
 * 		D:把排序后的字符数组转成字符串。
 */
public class StringTest { 
	public static void main(String[] args) {
		//定义一个字符串。
		String s = "egabdcf";
		
		//把字符串转换成字符数组。
		char[] chs = s.toCharArray();
		
		//对数组排序。模仿刚才的代码,把int改为char即可。
		for(int x=0; x<chs.length-1; x++){
			for(int y=0; y<chs.length-1-x; y++){
				if(chs[y]>chs[y+1]){
					char temp = chs[y];
					chs[y] = chs[y+1];
					chs[y+1] = temp;
				}
			}
		}
		
		//把排序后的字符数组转成字符串。
		String result = String.valueOf(chs);
		System.out.println(result);
	}
}


package HomeWork;
/*
 * A:模拟用户登录
 * 	分析: 
 * 		1.键盘录入账号密码
 * 		2.判断密码是否相同,如果相同,提示登录成功
 * 			如果不相同,提示再次输入,并提示剩余输入错与的次数
 * 		3.输入错误的次数为三次
 * */
public class TestUser {
//		成员变量
	private String userName = "Adim";
	private String code = "admin";
//	构造方法
	public TestUser(String userName, String code) {
		super();
		this.userName = userName;
		this.code = code;
	}
	public TestUser() {
		super();
	}
//	set\get方法
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	
	
}


package HomeWork3;
/*
 * 	需求 :键盘录入一个字符串 
 * 		统计字符串中大写字母,小写字母以及数字字符出现的次数
 * */
import java.util.Scanner;

public class TestBigSmallCount {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一个字符串");
		String str = sc.nextLine();
		tongJi(str);
	}

	public static void tongJi(String str) {
//		定义三个变量,分别表示记录大写字母,小写字母以及数字个数的变量
//		记录大写字母
		int bigCount = 0;
//		记录小写字母
		int smallCount = 0;
//		记录数字
		int number = 0;
//		定义一个变量,记录该字符串的长度
		int length = str.length();
		for (int i = 0; i < length; i++) {
			if(str.charAt(i)>='a' && str.charAt(i)<='z'){
				smallCount++;//判断如果是小写字母,则加一
			}else if(str.charAt(i)>='A' && str.charAt(i)<='Z'){
				 bigCount++;//判断是大写字母,则加一
			}else{
				number++;//剩下只有是数字,则加一
			}
		}
//		输出打印大写字母,小写字母以及数字的个数
		System.out.println("该字符串中包含大写字母"+bigCount+"个,"
							+"小写字母"+smallCount+"个"
							+"数字"+number+"个");
	}
	
	
}


(3)面试题
        A:字符串一旦被赋值,就不能被改变。
            内容不能被改变,引用可以改变。
        B:String s = new String("hello"); String s = "hello"的区别?
            前者创建了两个对象。
            后者创建了一个对象。
        C:写出程序的结果
          

 String s1 = new String("hello");
            String s2 = new String("hello");
            System.out.println(s1==s2); //false
            System.out.println(s1.equals(s2)); //true

            String s3 = new String("hello");
            String s4 = "hello";
            System.out.println(s3==s4); //false
            System.out.println(s3.equals(s4)); //true

            String s5 = "hello";
            String s6 = "hello";
            System.out.println(s5==s6); //true
            System.out.println(s5.equals(s6)); //true


        D:字符的比较
            String s7 = "中国";
            String s8 = "你好";
            String s9 = "中国你好";
            System.out.println(s9==s7+s8); //false 因为两个变量相加,首先会开辟空间,固然地址值是不可能相等的
            System.out.println(s9=="中国"+"你好");//true 因为两个常量相加,会先相加,然后再找是否有该常量,如果有,就将这个有的常量地址值赋值,固然是相等的


                         ----------------------android培训java培训、期待与您交流! ----------------------
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值