首页 技术 正文
技术 2022年11月14日
0 收藏 602 点赞 3,007 浏览 1838 个字

总结String类的常用方法

1. 获取字符串长度

 public int length()

2. 获取字符串某一位置的字符

public char charAt(int index)

注意:字符串中第一个字符索引是0,最后一个是length()-1。

3.获取字符串的子串

public String substring(int beginIndex)
//该方法从beginIndex位置起,
//从当前字符串中取出剩余的字符作为一个新的字符串返回。public String substring(int beginIndex, intendIndex)
//该方法从beginIndex位置起,从当前字符串中
//取出到endIndex-1位置的字符作为一个新的字符串返回。

4.字符串的比较

public int compareTo(String str)
//该方法是对字符串内容按字典顺序进行大小比较,
//通过返回的整数值指明当前字符串与参数字符串的大小关系。
//若当前对象比参数大则返回正整数,反之返回负整数,相等返回0。public int compareToIgnoreCase (String str)
//与compareTo方法相似,但忽略大小写。public boolean equals(Object obj)
//比较当前字符串和参数字符串,在两个字符串相等的时候返回true,否则返回false。public boolean equalsIgnoreCase(String str)
//与equals方法相似,但忽略大小写。

5.查找子串在字符串中的位置

public int indexOf(String str)
//用于查找当前字符串中字符或子串,返回字符或
//子串在当前字符串中从左边起首次出现的位置,若没有出现则返回-1。public int indexOf(String str, intfromIndex)
//改方法与第一种类似,区别在于该方法从fromIndex位置向后查找。public int lastIndexOf(String str)
//该方法与第一种类似,区别在于该方法从字符串的末尾位置向前查找。public int lastIndexOf(String str, intfromIndex)
//该方法与第二种方法类似,区别于该方法从fromIndex位置向前查找。

6.字符串中字符的大小写转换

public String toLowerCase()
//返回将当前字符串中所有字符转换成小写后的新串public String toUpperCase()
//返回将当前字符串中所有字符转换成大写后的新串

7.字符串两端去空格

String trim()
//去除字符串两端的空格,中间的空格不变,一般用于登陆注册时

8.将字符串分割成字符串数组

String[] split(String str)

9.基本类型转换为字符串

static String valueOf(xxx xx)//基本类型转化为字符串的三种方法
int c=10;
//包装类的toString方法
String str1=Integer.toString(c);
System.out.println("toString 方法转化的字符串:"+str1);
//使用String类的valueOf()方法
String str2=String.valueOf(c);
System.out.println("使用String类的valueOf()方法转化的字符串"+str2);
//一个空字符串加上基本类型,得到基本类型数据对应的字符串
String str3=c+"";
System.out.println("使用控制符串添加的到的字符串:"+str3);

10.替换字符串

public String replace(char oldChar, charnewChar)
//用字符newChar替换当前字符串中所有的oldChar字符,
//并返回一个新的字符串。public String replaceFirst(String regex,String replacement)
//该方法用字符replacement的内容替换当前字符串中遇到的
//第一个和字符串regex相匹配的子串,应将新的字符串返回。public String replaceAll(String regex,String replacement)
//该方法用字符replacement的内容替换当前字符串中遇到的所有
//和字符串regex相匹配的子串,应将新的字符串返回。
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,497
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,135
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,298