10天轻松学习javase第3天下,Java内置类 String类使用完成脏话过滤小练习

10天轻松学习javase第3天下,Java内置类 String类使用完成脏话过滤小练习
Java中的引用类型共有三种,分别是类,数组,接口这些引用类型的默认值都是null

内置类也是类,属于引用类型又叫复合类型。

String类代表字符串。 Java程序中的所有字符串文字(例如"abc" )都被实现为此类的实例。

String类的使用:

定义一个字符串变量:

String author= “matudy”;

String常用的方法:

/*1定义一个字符串变量
* 1、字符串比较compareTo、compareToIgnoreCase
* 2、字符串查找indexOf、lastIndexOf
* 3、删除字符串
* 4、字符串替代replace、replaceAll
* 5、字符串反转reverse
* 6、字符串转变大小写toUpperCase、toLowerCase
* 7、去掉首位空格trim
* 8、是否包含某字符/字符串contains
* 9、返回指定位置字符charAt
*/


package javaseof10day.day4.am;

import java.util.Date;

import javax.swing.Spring;

public class StringDemo {

	public static void main(String[] args) {

		//1定义一个字符串变量
		String author= "matudy";
		System.out.println(author);
		
		//2求author字符串变量的长度
		System.out.println(	"author字符串变量的长度"+author.length());
		
	//	3String 字符串通过 "+" 操作符和StringBuffer.append() 方法来连接字符串。
		String subject="IT123私塾之";
		String bookname="《10天轻松学习Javase教程》";
		String title=subject+bookname;
		System.out.println("+方式连接两个字符串方便简单:"+title);
	    StringBuffer title2 = new StringBuffer();		
	    title2.append(subject);
	    title2.append(bookname);
	    System.out.println("StringBuffer.append方式连接字符串:"+title2);
		
		
	//4 比较两个字符串是否相同可以用==  或者equals方法
	//"=="代表比较双方是否相同。如果是基本类型则表示值相等,如果是引用类型则表示地址相等即是同一个对象。

	//Object 的 equals 方法默认就是比较两个对象的hashcode,是同一个对象的引用时返回 true 否则返回 false。
		
	String	str1="mastudy";
	String	str2="mastudy";
	System.out.println("=号测试"+(str1==str2));
	System.out.println("equals测试"+(str1.equals(str2)));

		
	//	5String contains字符串是否包含  字符串
	System.out.println("str1字符串是否包含str2字符串"+str1.contains(str2));
	

//6 String toUpperCase() 方法将字符串从小写转为大写。
	System.out.println("toUpperCase() 方法将字符串从小写转为大写。"+author.toUpperCase());

	
	/*作业:
1定义一个字符串变量
	 * 1、字符串比较compareTo、compareToIgnoreCase 
	 * 2、字符串查找indexOf、lastIndexOf 
	 * 3、删除字符串
	 * 4、字符串替代replace、replaceAll 
	 * 5、字符串反转reverse 
	 * 6、字符串转变大小写toUpperCase、toLowerCase
	 * 7、去掉首位空格trim 
	 * 8、是否包含某字符/字符串contains 
	 * 9、返回指定位置字符charAt
	 */

	
	
	}


}

脏话过滤的小例子:


package javaseof10day.day4.am;

import java.util.ArrayList;
import java.util.List;

public class Action {
	
	

    private static List<String> list = new ArrayList<String>();
    static{
        
        list.add("骂人");
        list.add("sb");
        list.add("妈的");
        list.add("他妈的");

    }
    public static List<String> getlist(){
        return list;
    }
	
	
	

	public static String WordFilter(String word) {
		if (word == null || word == "") {
			return null;

		}
		
		
		
		
		List<String> list = Action.getlist();
		for (String str : list) {
			word = word.replaceAll(str, "***");
		}


		return word;
	}

}


import java.util.Date;

import javax.swing.Spring;

public class day3AmDemo {

	public static void main(String[] args) {
		
	//脏话过滤练习
	  String resString = Action.WordFilter("妈的");
		
		System.out.println(resString);
		
		
		}


}
发布了55 篇原创文章 · 获赞 1 · 访问量 2951

猜你喜欢

转载自blog.csdn.net/u013750652/article/details/104040921
今日推荐