对字符串的几种简单操作

2019-11-2

对字符串的操作

String 也是一个类,类似于数组;
定义:
String str = “asdfghgfdsa”;
几种简单操作字符串的方法:
(1)字符串替换:
str = str.replace(“s”,”e”); 将str中的s换成e;
例:

public class Test{
	public static void main(String[] args){
		String str = "asdfghgfdsa";
		str = str.replace("s","e");
		System.out.println(str);
	}
}

输出结果:

aedfghgfdea

(2)字符串分割
String[] s = str.split("f"); 从字符为f的地方分割开。
例:

import java.util.*;
public class Test{
	public static void main(String[] args){
		String str = "asdfghgfdsa";
		String[] s = str.split("f");
		System.out.println(Arrays.toString(s));
	}
}

输出结果:

[asd, ghg, dsa]

(3)字符串求长:
str.length();后面必须有括号;
例:

public class Test{
	public static void main(String[] args){
		String str = "asdfghgfdsa";
		
		System.out.println(str.length());
	}
}

输出结果:

11

(4)字符串定位:
1、 知道角标找内容:str.charAt();
例:

public class Test{
	public static void main(String[] args){
		String str = "asdfghgfdsa";
		System.out.println(str.charAt(6));
	}
}

输出结果:

g

2、 知道内容找角标:
从前往后找str.indexOf(“字符串”);
例:

public class Test{
	public static void main(String[] args){
		String str = "asdfghgfdsa";
		System.out.println(str.indexOf('s'));
	}
}

输出结果:

1

从后往前找str.lastIndexOf(“字符串”);
例:

public class Test{
	public static void main(String[] args){
		String str = "asdfghgfdsa";
		System.out.println(str.lastIndexOf('s'));
	}
}

输出结果:

9

从指定位置开始找 str.indexOf(“要找的字符”,从某个位置开始);
例:

public class Test{
	public static void main(String[] args){
		String str = "asdfghgfdsa";
		System.out.println(str.indexOf('s',2));
	}
}

输出结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值