《1》String类的四种构造方法
//方式一
String s1 = new String(“hello”);
//方式二
char[] chs ={‘h’,’e’,’l’,’l’,’o’};
//方式三
String s3 =new String(chs,1,3);
//方式四
String s4 =”hello”;
《2》通过构造方法创建字符串和直接赋值创建字符串的区别
在内存的位置不同
构造方法是在堆内存
直接赋值是在方法去的常量池
《3》String类的判断功能
判断主要是掌握equals方法 实现模拟登录功能,给三次机会,并提示还有几次机会
public class Login {
// 实现模拟登录功能,给三次机会,并提示还有几次机会
public static void main(String[] args) {
String username = "admin";
String password = "123";
for(int i=0;i<3;i++)
{
System.out.println("-------欢迎来到登录系统-------");
Scanner bi = new Scanner(System.in);
System.out.println("请输入用户名:");
String name = bi.nextLine();
System.out.println("请输入密码:");
String pwd = bi.nextLine();
if(username.equals(name) && password.equals(pwd))
{
System.out.println("登录成功");
break;
}else
{
if((2-i)==0)
{
System.out.println("账号被锁定,请与管理员联系");
}
else
{
System.out.println("你还有"+(2-i)+"次机会");
}
}
}
}
}
注:
“==”和equals方法有什么区别?
==和equals方法都可以用来比较两个对象是否是同一个对象。
==还可以比较两个变量的值是否相等。
equals是Object类中的方法,可以由子类重写此方法,实现内容相等。
《3》String 的一些常用方法
charAt() 获取指定角标的字符
indexOf() 获取字符串对象第一次出现的角标
subString() 截取字符串
toCharArray() 将字符串转化为数组 =>会用for循环进行编写
toLowerCase() 将字符串大写转小写 toUpperCase() 小写转大写
split() 指定符号分隔字符串
案例:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
public class getCount {
// 统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
public static void main(String[] args) {
Scanner bi = new Scanner(System.in);
System.out.println("请输入你要输入的字符串:");
String s = bi.nextLine();
int bigCount = 0;
int smallCount =0;
int numCount =0;
for(int i=0;i<s.length();i++)
{
char ch = s.charAt(i);
if(ch>='A' && ch<='Z')
{
bigCount++;
}
else if(ch>='a' && ch<='z')
{
smallCount++;
}
else if(ch>='0' && ch<='9')
{
numCount++;
}
}
System.out.println("大写字母出现的次数:"+bigCount);
System.out.println("大写字母出现的次数:"+smallCount);
System.out.println("大写字母出现的次数:"+numCount);
}
}