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.out.println("区号正确");
              }else
                {
                   System.out.println("区号有误!");
                }
               //座机右侧:029-123456
               int starRight=end+1;
               String numberStr= phone.substring(starRight);
               if (numberStr.length()==8)
              {
                   System.out.println("号码正确");
              }else
                {
                   System.out.println("号码有误!");
                }
          }else
            {
               System.out.println("手机号码");
            }
      }

   public static void testSubstring2(String phone)
  {
       //029-23456645
       // String phone="18055555555";
       //座机要求:区号是3或4位,右侧8位
      // String phone="123456";
       if (phone.indexOf("-")!=-1)
      {
           System.out.println("座机号码");
           //   区号是3或4位,右侧8位
           //截取区号
           int start = 0;
           int end = phone.indexOf("-");
           String zone = phone.substring(start, end);
           int starRight = end + 1;
           String numberStr = phone.substring(starRight);
           //正确:区号正确 且号码正确
           //座机右侧:029-123456
           if ((zone.length() == 3 || zone.length() == 4)&&(numberStr.length()==8))
          {
               System.out.println("座机正确");
          }else
            {
               System.out.println("座机不正确!");
            }
           
      }else
        {
           //1888888
           System.out.println("手机号码");
           String first=phone.substring(0,1);
           if (first.equals("1")&& phone.length()==11)
          {
               System.out.println("正确的");
          }else
            {
               System.out.println("错误的手机");
            }

        }

  }

   public static void testSplit()
  {
       //"043-45464677";
       String phone="029-23456645";  //拆完后是数组
       String [] ps=phone.split("-");
//       System.out.println(ps[0]);
//       System.out.println(ps[1]);
       //也可以遍历
       for (String p:ps)
      {
           System.out.println(p);
      }
  }


//static--->static
   public static void main(String[] args)
  {
         boolean result=isValidateEmail("1234567@qq.com");
          System.out.println(result==true?"合法":"不合法");
            testSubstring();
        testSubstring2("029-54354457");

        //split(); 字符串拆分
       testSplit();

  }
}
  • 字符串常量池:

package Demo01;

public class StringDemo02
{
   public static void main(String[] args)
  {
//       int num=10;
//       num=11;
//       System.out.println(num);//11
       String str="a";
       str="b";
       System.out.println(str); //b
       /*
final定义在类里面是不能继承,而定义在变量前面,变量不能改变
*/

       String str1="hello";
       String str2="hello";
       System.out.println(str1==str2); //true
       
       String str3=new String("hello");
       String str4=new String("hello");
       String str5=new String("hello");
       
       System.out.println("str==str2"+str2);  //做字符串拼接
       System.out.println("str==str2"+(str3==str4));//false   因为两个都开辟了各自的新空间
       System.out.println("str==str2"+(str1==str4));//false
       String str6=new String("abc")+"abc";
       System.out.println(str6);

       str4=str4.intern();//inten方法,可以让引用直接指向常量池
       System.out.println("str1==str4"+(str1==str4)); //true

            //如果用==来比较两个字符串,那么实际上你是在比较两个字符串的内存引用地址,
           // 一般来说是不相同的,但是java编译器不会报错!
           //因为java认为你在比较两个字符串的内存引用地址。如果要比较两个字符串内容是否相同,
           // 需要使用equals行数。
    }
}

  •  

    习题:

//练习
package Demo01;

import java.util.StringTokenizer;

public class StringDemo03
{
   //splic :特殊符号不适应: . | \ $ + * ,如果要用加\\
   public static void test01()
  {
       String str="hello|world";
       String [] split=str.split("\\|");
       for (int i=0;i<split.length;i++)
      {
           System.out.println(split[i]);
      }
  }
   public static void test02()
  {
       String str="hello|world";
       StringTokenizer token=new StringTokenizer(str,"|");
       token.hasMoreElements(); //判断是否有下一个元素
       while (token.hasMoreElements())
      {
           System.out.println(token.nextElement());
      }
  }

   //输入一个字符串,统计该字符串中某个单字符串出现的次数
   /*
   helloworld : 1
   hellowrold-->{"h","e","l","l","0","w","r","0".....} 每拆(截)一个填一个就在{}里面
   如果用split拆分 :拆分符号正好在末尾,则末尾的字符无法被统计。
    */
//   input: helloworld
public static int test03(String input,String word)
{
   int count=0;

   String [] strs=new String[input.length()];
    for (int i=0;i<input.length();i++)
  {
       strs [i]= input.substring(i,i+1); // [i,i+1) 取第一个变量
       System.out.println(strs[i]);
       if (strs[i].equals(word))    //统计某个字出现几次
      {
          count++;
      }
  }
    //return 1;
    return count;
}

//input:helloworld "low",判断一个字符串中,某个子字符串出现的次数
   public static int test04(String input,String word)
  {
       /*
       input:helloworld   ,判断前三个是不是llo ,+1
        */
//       int position= input.indexOf("llo");//如果有多个llo只能检测第一个llo
//       System.out.println(position);

       int count=0;
       while (input.indexOf("llo") !=-1) //有多少个llo就检测出来,
      {
           count++;
           input=input.substring(input.indexOf("llo")+1);
      }
       return count;

  }

   public static void main(String[] args)
  {

       //test02();
      // System.out.println( test03("helloworld","o"));
       //test04("helloworld","llo"); //2
       System.out.println(test04("helloworld","llo")); //1
  }
}

test02()思路

package Demo01;
public class StringDemo04
{
   public static void test01()
  {
       //indexof("子字符串"):子字符串在源字符中的位置
       //位置--->字符
       String str="helloworld";
       int position=str.indexOf("llo");
       System.out.println(position);   //2

       //根据位置找字符
       char c=str.charAt(2);
       System.out.println(c);//l

       //replace 替换
       System.out.println(str);
       str=str.replace('d','y');
       System.out.println(str);
       //多个参数替换
       str=str.replace("hel","AAA");
       System.out.println(str);
  }
   public static void main(String[] args)
  {

  }
}
  • StringBuffer使用:

package Demo01;
/*
StringBuffer:String的增强版,比String最大的升级:可以在原来的内存空间中直接修改变量值
*/
public class JavaBufferDemo
{
   public static void test01()
  {
       StringBuffer sb=new StringBuffer("abc");  //类似于String str="abc";
       //str+="aaa";
       sb.append("aaa");//追加拼接
       System.out.println(sb);  //abcaaa
       //abcaaa
       sb.insert(2,"bbb");  //插入
       System.out.println(sb);//abbbbcaaa
       sb.reverse();//逆序
       System.out.println(sb);

       //String--->StringBuffer各自独立, 可以相互转换
       //String--->StringBuffer
       String a="hello";
       StringBuffer sb2=new StringBuffer(a);
       //StringBuffer--->String
       String b= sb2.toString();   //因为万物都继承Object基类,里面有一个方法toString();
       System.out.println(b);
       String c=sb2+"";  //任何类型遇到字符串都转换字符串
  }

   //"12345678"---->123,345,678   从后面开始数没三个数一个逗号
   public static void test02(String digital)
  {
       StringBuffer sb=new StringBuffer(digital); //转为StringBuffer
       for (int i=digital.length()-3;i>0;i=i-3)
      {
           sb.insert(i,",");
      }
       System.out.println(sb);
  }

   public static void main(String[] args)
  {
       test01();
       test02("12345678");
  }
}

    计算字符串中子字符串的出现的次数:

package Demo01;
import java.util.Scanner;

public class StrCount
{
   public static void main(String[] args)
  {
       Scanner scanner=new Scanner(System.in) ;
       System.out.println("请输入一个字符串");
       String s=scanner.nextLine();
       System.out.println("请输入查找的字符串");
       String s1=scanner.nextLine();
       int count=0;
       while (s.indexOf(s1)!=-1)
      {
           count++;
           s=s.substring(s.indexOf(s1)+1);
      }
       System.out.println(s1+"在"+"中的首都都是北京,北京很大!"+"出现的次数为"+count);
  }
}

实现java工程师的注册:

package Demo01;
import java.util.Scanner;

public class EngRegister
{
   public static boolean verify(String name,String pwd1,String pwd2)
  {
       if(name.length()>6&&pwd1.length()>8) //判断用户名否大于6 和 密码是否大于8
      {
           //如果用==来比较两个字符串,那么实际上你是在比较两个字符串的内存引用地址,
           // 一般来说是不相同的,但是java编译器不会报错!
           //因为java认为你在比较两个字符串的内存引用地址。如果要比较两个字符串内容是否相同,
           // 需要使用equals行数。
           if (pwd1.equals(pwd1))    //判断两次密码是否一致
          {
               System.out.println("注册成功!请牢记用户名和密码");
          }
           else {
               System.out.println("两次输入的密码不相同");
          }
      }else {
           System.out.println("用户名长度不能小于6,密码长度不能小于8!");
      }
       return  true;
  }
   public static void main(String[] args)
  {
       Scanner input=new Scanner(System.in);
       String engName,p1,p2;
       boolean resp=false;
       do {
        resp=true;

      }while (!resp);
      {
           System.out.println("请输入java工程师用户名:");
           engName=input.nextLine();
           System.out.println("请输入密码:");
           p1=input.nextLine();
           System.out.println("请在次输入密码:");
           p2=input.nextLine();
           verify(engName,p1,p2);
      }
  }
}

实现交论文信息校验 :

package Demo01;
import java.util.Scanner;

public class FileUpload
{
   public static void main(String[] args)
  {
       System.out.println("请按照一下要求提交论文");
       Scanner scanner=new Scanner(System.in);
       System.out.println("请输入论文文件名(必须以.docx结尾:)");
       String s1=scanner.nextLine();
       System.out.println("请输入接收论文反馈 的邮箱:");
       String s2=scanner.nextLine();
      // String s3=s1.substring()
       String str=".docx";

       if (s1.endsWith(str))  //结尾判断
      {
           if (s2.indexOf("@")!=-1&&s2.indexOf(".")!=-1&&s2.indexOf("@")<s2.indexOf("."))
          {
               System.out.println("论文提交成功");

          }else {
               System.out.println("邮箱无效");
               System.out.println("论文提交失败");
          }
      }else {
           System.out.println("文件名无效");
           System.out.println("论文提交失败");
      }
  }
}

posted @ 2022-09-12 21:35  zjw_rp  阅读(54)  评论(0)    收藏  举报