JAVA类—String类(一)

String类
1 字符串的声明
   java中用字符串" "括起来
   字符串的声明:String 字符串name;
    声明及初始化:String str="hello";
2 创建字符串
  用一个字符数组创建一个对象
  char[] s={'h','e','l','l','o'};
  String str=new String(a);
  等价于String str=new String("hello");
  提取字符数组中一部分创建一个字符串对象
  char[] a={'s','t','u','d','e','n','t'};
  String str=new String(a,2,4);
  等价于String str=new String("uden");
  引用字符串常量来创建字符串变量
  String str1,str2;
  str1="hello"
  str2="hello"
  此时Str1与Str2引用相同的字符串常量因此具有相同的实体。
3 连接字符串
  public static void main(String[] args) {
		String s1="hello";
		String s2="java";
		String s=s1+" "+s2;
		System.out.println(s);
	}
4 获取字符串长度
  public static void main(String[] args) {
		String s1="hello";
		String s2="java";
		int size1=s1.length();
		int size2=s2.length();
		System.out.println(size1);
		System.out.println(size2);
	}
5 字符串的查找
  public class test {
	public static void main(String[] args) {
		String s1="hello";
		String s2="java";
		int size01=s1.indexOf("e");
		int size02=s2.lastIndexOf("a");
		char c=s1.charAt(4);
		System.out.println(c);
		System.out.println(size01);
		System.out.println(size02);
		
	}
}
6 获取子字符串 (字符串中空格占用一个索引)
  public class test {
	public static void main(String[] args) {
		String s1="hello";
		String s2="java";
		String str=s1.substring(3);
		String str2=s2.substring(0,3);
		String str1=s2.substring(1,3);左闭右开
		System.out.println(str2);
		System.out.println(str);
		System.out.println(str1);
		
	}
}
7 去除空格
  public class test {
	public static void main(String[] args) {
		String s1="  hello   java  ";
		System.out.println(s1.length());
		System.out.println(s1.trim().length());
		
	}
}
8 字符串的替换
  replace()方法将指定的字符或字符串换成新的字符或字符串
  public class test {
	public static void main(String[] args) {
		String str="address";
		String newstr=str.replaceAll("a", "A");
		System.out.println(newstr);
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值