String类主要方法的使用:
1、获取长度 .length();//这与数组中的获取长度不同,.length;
2、比较字符串(1) equals() //判断内容是否相同
(2)compareTo() //判断字符串的大小关系
(3)compareToIgnoreCase(String int) //在比较时忽略字母大小写
(4)== //判断内容与地址是否相同
(5)equalsIgnoreCase() //忽略大小写的情况下判断内容是否相同
如果想对字符串中的部分内容是否相同进行比较,可以用
(6)reagionMatches() //有两种 public boolean regionMatches(int toffset, String other,int ooffset,int len);表示如果String对象的一个子字符串与参数other的一个子字符串是相同的字符序列,则为true.要比较的String 对象的字符串从索引toffset开始,other的字符串从索引ooffset开始,长度为len。等等…
String类中提供了大量的操作方法,这里例举14种关于String类常用的方法。参考代码如下:
public class StringTestMc {
private String str = “helloWorld”;
/**
* 将字符串变成一个字符数组
/
public void tochary() {
char c[] = str.toCharArray();
for (int i = 0; i < c.length; i++) {
System.out.println(“转为数组输出:” + c[i]);
}
}
/*
* 从字符串中取出指定位置的字符
/
public void tocharAt() {
char c = str.charAt(3);
System.out.println(“指定字符为:” + c);
}
/*
* 将字符串变成一个byte数组
/
public void tobyte() {
byte b[] = str.getBytes();
System.out.println(“转换成byte数组输出为:” + new String(b));
}
/*
* 取得一个字符串的长度
/
public void tolength() {
int l = str.length();
System.out.println(“这个字符串的长度为:” + l);
}
/*
* 查找一个指定的字符串是否存在,返回的是字符串的位置,如果不存在,则返回-1
/
public void toindexOf() {
int a1 = str.indexOf(“e”);// 查找字符e的位置
int a2 = str.indexOf(“l”, 2);// 查找l的位置,从第3个开始查找
System.out.println(“e的位置为:” + a1);
System.out.println(“l的位置为:” + a2);
}
/*
* 去掉字符串左右空格
/
public void totrim() {
String str1 = " hello ";
System.out.println(“去掉左右空格后输出:” + str1.trim());
}
/*
* 字符串的截取
/
public void tosubstring() {
System.out.println(“截取后的字符为:” + str.substring(0, 3));// 截取0-3个位置的内容
System.out.println(“从第3个位置开始截取:” + str.substring(2));// 从第3个位置开始截取
}
/*
* 按照指定的字符串拆分字符,拆分的数据将以字符串数组的形式返回
/
public void tosplit() {
String s[] = str.split(“e”);// 按hello中的e进行字符串拆分
for (int i = 0; i < s.length; i++) {
System.out.println(“拆分后结果为:” + s[i]);
}
}
/*
* 将字符串进行大小写转换
/
public void tochange() {
System.out.println(“将"hello"转换成大写为:” + str.toUpperCase());// 将hello转换成大写
System.out.println(“将"HELLO"转换成大写为:”
+ str.toUpperCase().toLowerCase());// 将HELLO转换成小写
}
/*
* 判断是否以指定的字符串开头或者结尾
/
public void tostartsWithOrendWith()
{
if(str.startsWith(“he”))//判断字符串是否以he开头
{
System.out.println(“字符串是以he开头”);
}
if(str.endsWith(“lo”))
{
System.out.println(“字符串是以lo结尾”);
}
}
/*
* 两个String类型内容比较
/
public void toequals()
{
String str3=“world”;
if(str.equals(str3))
{
System.out.println(“这俩个String类型的值相等”);
}
else
System.out.println(“这俩个String类型的不值相等”);
}
/*
* 两个字符串不区分大小写进行比较
/
public void toequalslgnoreCase()
{
String str4=“HELLO”;
if(str.equalsIgnoreCase(str4))
{
System.out.println(“hello和HELLO忽略大小写比较值相等”);
}
}
/*
/**
* 判断两个字符串是否相等
*/
public void judge()
{
String str5=“HELLO”;
String str6=“HELLO”;
if(str5==str6)
System.out.println(“字符串相等”);
}