String及常见方法
String常见方法
public class string1 {
static String name;
public static void main(String[] args) {
// String name1;
String name2 = "abcd";
String name3 = new String();
System.out.println(name);
System.out.println(name2);
System.out.println(name3);
System.out.println(name3.equals(""));
System.out.println(name3 == null);
}
}
通用理论:
-
对于非基本类型(对象类型或引用类型)
-
只定义,不实例化(new),其默认值为null
例如:String name、People person
-
实例化
`String name3 = new String()值为"",但name3的属性值全是目前全部是默认值(null,0)
-
几种常用的方法
- s.equals(),比较字符串是否相等
- s.toUpperCase(),字符串大小写转换
- s.indexOf(),判断字符串A是否存在与字符串B中,如果存在返回位置,不存在返回-1
- s.lastindexOf(),与indexOf()使用相同寻找位置倒序查找
- s.length(),获取字符串长度
- s.trim(),去掉首尾空格但不会去掉中间的空格
案例
座机号码检查
import java.util.Scanner;
public class stringAnli {
static int count = 0;
public static void main(String[] args) {
testSub();
}
public static void testSub(){
do {
System.out.print("输入号码" + ":");
String telephone = new Scanner(System.in).nextLine();
if (telephone.indexOf("-") != -1){
System.out.println("座机号");
//截取区号
int start = 0;
int end = telephone.indexOf("-");
String num = telephone.substring(start,end);
int telephRight = end + 1;
String numRight = telephone.substring(telephRight);
if ((num.length() == 3 || num.length() == 4) && (numRight.length() == 8)){
System.out.println("座机正确");
}else{
System.out.println("座机错误");
}
}else if(telephone.length() == 11) {
System.out.println("手机号");
}else {
System.out.println("非法号码");
}
count++;
System.out.println("目前已经输入" + count + "个号码");
}while (count < 8);
}
}