String字符串常用的提取方法&驗證郵箱的格式是否符合規范


indexOf(a): a可以是字符串,字符,整型(ASICC碼),返回的是第一次出現的位置,如果不存在a,則返回-1,返回的結果是int型

indexOf(a,int): int的作用是跳過前幾個開始往后找下一個出現a的位置,返回的結果是int型

lastIndexOf(a):返回最后一次出現的位置,返回的結果是int型

lastIndexOf(a,int):返回最后一次出現的位置,所找的位置在從下標0開始到下標int結束的區間內,返回的結果是int型

endWith("str"):以str結尾,返回的結果是boolean型

startWith("str"):以str開始,返回的結果是boolean型

contains("str"):包含str,返回的結果是boolean型

trim():去掉字符串前后的空格,字符串中間的空格是不能去掉的,返回的結果是一個新的字符串String,不改變原來的字符串

split("a"):以a為分隔符分割字符串,返回一個String類型的數組

subString(a):截取a位置開始到最后的所有字符串,包括a

subString(a,b):截取a位置到b位置的字符串,包括a,不包括b

replace("str1",”str2“):將原字符串中的所有的str1用str2代替,返回一個新的字符串,不改變原來的字符串

replaceFirst("str1",”str2“):將原字符串中的第一次出現的str1用str2代替,返回一個新的字符串,不改變原來的字符串

indexOf(a)

 1 package myeclipseFiles2;
 2 
 3 public class String2 {
 4 public static void main(String[] args) {
 5     String str="azttlxx@qq.com";
 6     int a=str.indexOf("x");//字符串  7     int b=str.indexOf('x');//字符  8     int c=str.indexOf(120);//整型,對應ASICC碼中的x  9     System.out.println(a);//返回結果是  5
10     System.out.println(b);//返回結果是  5
11     System.out.println(c);//返回結果是  5
12 }
13 }
1 package myeclipseFiles2;
2 
3 public class String2 {
4 public static void main(String[] args) {
5     String str="azttlxx@qq.com";
6     int a=str.indexOf("xx@");
7     System.out.println(a);//返回結果是  5   返回的是字符串中首位所在的位置
8 }
9 }

 

indexOf(a,int):

1 package myeclipseFiles2;
2 
3 public class String2 {
4 public static void main(String[] args) {
5     String str="xzttlxx@qq.com";
6     int a=str.indexOf("x",3);//跳過前三個"xzt",找下一個出現"x"的位置 7     System.out.println(a);//返回結果是  5
8 }
9 }

 

lastIndexOf(a,int):

1 package myeclipseFiles2;
2 
3 public class String3 {
4 public static void main(String[] args) {
5     String str="zttlxxztt@qq.com";
6     int a=str.lastIndexOf("t",4);
7     System.out.println(a);//返回結果  2
8 }
9 }

 

驗證郵箱:

 

 1 package myeclipseFiles2;
 2 
 3 import java.util.Scanner;
 4 
 5 public class String2 {
 6 public static void main(String[] args) {
 7     while(true){
 8         System.out.print("請輸入一個郵箱地址:");
 9         Scanner sc=new Scanner(System.in);
10         //123@qq.com   3   9-6
11         String str=sc.next();
12         //判斷是否是QQ郵箱 只有一個@ .   
13         int a1=str.indexOf("@qq.com");
14         int a2=str.lastIndexOf("@qq.com");
15         int b1=str.indexOf("@");
16         int b2=str.lastIndexOf("@");
17         int c1=str.indexOf(".");
18         int c2=str.lastIndexOf(".");
19         if(a1>0 && a1==a2 &&a1==str.length()-7&& b1==b2 && c1==c2){
20             System.out.println("這是一個正確的郵箱地址格式");
21         }else{
22             System.out.println("這是一個錯誤的郵箱地址格式");
23         }
24     }
25     
26 }
27 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM