Java学习(一):字符串

一个java文件中只能有一个public类

例:public class hello{}

hello:类名,公共类的类名必须与文件名一样

public class hello{
   public static void main(String args[]){
   System.out.println("hello!");
   }
}

输出 :hello!



public class Number{
   public static void main(String args[]){  //主方法
   int num=2;
   System.out.println("result="+result);
   }
}

声明常量:

final double PI = 3.1415926D;   //声明double加d或D无影响,但是声明float类型时,不加f会默认为double型,产生错误。

关键字static:

static int x = 9 ;  //设置静态变量

foreach语句:

for(元素变量x:遍历对象 obj)
{
     引用了x的Java语句;
}

例:
int arr[]={7,10,1};
for(int x:arr)
{
     System.out.println(x);
}//遍历数组

标签跳出:

标签名:循环体{
       break 标签名;
}

链接字符串:

String s1 = new String("Hello");
String s2 = new String("world");
String s = s1 + " "+ s2;

字符串查找:


String str = "Hello World";
int size = str.indexOf("l");
//size值为2;s顺序查找l在str中的位置;lastIndexO(String str)为逆序查找

获取子字符串:

String str ="Hello World";
String substr=str.substring(3);
//substr的值为lo World
//String substr = str.substring(0,3);//截取第1位到第3位

字符串替换:

String str="address";
String newstr=str.replace("a","A");
//把str的a全部替换为A

判断字符串的开始和结尾

判断开始:startsWith();
判断结尾:endsWith();
例:
String num1 = "22045612";
String num2 = "21465448";
boolean b = num1.startsWith("22");  //b值为true
boolean b2 = num2.endsWith("44");  //b2值为false

判断字符串有相同字符和长度

str.equals(String otherstr)  //区分大小写
str.equalsgnoreCase(String otherstr)   //不区分大小写

字符串大小写转换

String str1=str.toLowerCase();  //变小写
str.toUpperCase();//变大写







    


猜你喜欢

转载自blog.csdn.net/SCP_343/article/details/80929850
今日推荐