String字符串
-
字符串常见方法:
package Demo01;
public class StringDemo
{
String s3; //全局变量有默认值
//字符串基本操作
public static void test1()
{
//定义字符串方式1;
String s="abcd";
System.out.println(s);
//基本类型 int num=10;
//对象类型:Person per=new Person();
//定义字符串方式2;
String s1=new String("helloworld");
System.out.println(s1);
//方式3
String s2=new String();//默认生成的s2是“”
System.out.println(s2.equals(""));//"" true
System.out.println(s2==null);//null false
//局部变量使用前必须赋初值
/*
通用理论:对于非基本类型,(对象类型|引用类型)
1.只定义,不new, 默认值都是null
Person per;
String s3;
2.new实例化: Xxx xx=new Xxx();
xx值:不是null
xx内部的属性值 目前 全部是数据类型的默认值:
就是“空(数据类型的默认值)”
String S3=new String();S3:“ ”
Person per=new Person(); per:name是null age是0
(String name,int age)
0
0
false....
对象类型默认值:null
*/
//常用的String方法
String str="helloworld ";
boolean flag=str.equals("helloWorld");//equals()判断相等
boolean flag2=str.equalsIgnoreCase("HelloWorld");//忽略大小写
System.out.println(flag);
System.out.println(flag2);
int len=str.length(); //获取长度
System.out.println(len);
//转为大写
str.toUpperCase();
System.out.println(str);
//小写
str=str.toLowerCase();
System.out.println(str);
//helloworld 找关键字
//判断 字符串A是否存在于另一个字符串b中,如果存在,则返回位置:如果不存在,返回-1
int position = str.indexOf("owo"); //char----int
System.out.println(position);
//倒着找 lastIndexOf
//去除空格
System.out.println(str.length());
str=str.trim();//首尾两端,中间不会去掉
System.out.println("去掉首尾空格"+str);
}
//验证邮箱是否 合法 12345678@qq.com 123456.com不合法
public static boolean isValidateEmail(String email)
{
//合法情况
if (email.indexOf("@")!=-1 && email.indexOf(".")!=-1&&email.indexOf("@")<email.indexOf("."))
{
return true;
}
return false;
}
//校验 电话是否合法
public static void testSubstring()
{
//029-23456645
//座机要求:区号是3或4位,右侧8位
// String phone="18055555555";
String phone="029-123456";
if (phone.indexOf("-")!=-1)
{
System.out.println("座机号码");
// phone.substring(start,end); [start,end)
// phone= phone.substring(2,6);// >=2 <6// 字符串内置方法
// System.out.println(phone);
// 区号是3或4位,右侧8位
//截取区号
int start=0;
int end=phone.indexOf("-");
String zone=phone.substring(start,end);
if (zone.length()==3||zone.length()==4)
{
System.