java 字符串操作
一、相关知识学习
String类对象的常用方法
- public String concat(String str)
字符串的连接,作用是将参数中的字符串str连接到原来字符串的后面 - public int length()
求字符串的长度 - public char charAt(int index)
求字符串中某一位置的字符 - public int compareTo(String anotherString)
比较的是两个字符串数据 - public boolean equals(Object anObject)
比较当前字符串和参数字符串,在两个字符串相等的时候返回true,否则返回false - public boolean equalsIgnoreCase(String anotherString)
和equals方法相似,不同的地方在于,equalsIgnoreCase方法将忽略字母大小写的区别 - public String substring(int beginIndex)
从beginIndex位置起,从当前字符串中取出剩余的字符作为一个新的字符串返回 - public String substring(int beginIndex,int endIndex)
该子串从beginIndex位置起至endIndex-1为结束.子串返的长度为endIndex-beginIndex - public int indexOf(int ch)
用于查找当前字符串中某一个特定字符ch出现的位置,该方法从头向后查找,如果在字符串中找到字符ch,则返回字符ch在字符串中第一次出现的位置;如果在整个字符串中没有找到字符ch,则返回-1 - public int indexOf(int ch, int fromIndex)
该方法从fromIndex位置向后查找,返回的仍然是字符ch在字符串第一次出现的位置 - public int lastIndexOf(int ch)
该方法从字符串的末尾位置向前查找,返回的仍然是字符ch在字符串第一次出现的位置 - public int lastIndexOf(int ch, int fromIndex)
该方法从fromIndex位置向前查找,返回的仍然是字符ch在字符串第一次出现的位置 - public String toLowerCase()
该方法将字符串中所有字符转换成小写,并返回转换后的新串 - public String toUpperCase()
该方法将字符串中所有字符转换成大写,并返回转换后的新串 - public String trim()
该方法只是去掉开头和结尾的空格,并返回得到的新字符串 - public String replace(char oldChar,char newChar)
该方法用字符newChar替换当前字符串中所有的字符oldChar,并返回一个新的字符串 - public String replaceFirst(String regex,String replacement)
该方法用字符串replacement的内容替换当前字符串中遇到的第一个和字符串regex相一致的子串,并将产生的新字符串返回 - public String replaceAll(String regex,String replacement)
该方法用字符串replacement的内容替换当前字符串中遇到的所有和字符串regex相一致的子串,并将产生的新字符串返回
二、训练
任务要求:
- 完成一个java application应用程序,完成字符串的各种操作。
- 操作包括字符串的初始化赋值和输出。
- 操作包括两个字符串相加合成为一个新字符串。
- 操作包括两个字符串比较其是否相同。
- 操作包括已知一个字符串,查找某一子字符串是否被包含在此字符串之中,如果包含,包含了多少次。
- 操作包括已知一个字符串及其包含的某一子字符串,把此子字符串替换为其他的新的指定字符串。
java程序(test1.java)
public class test1 {
public static void main(String[] args) {
String s1="Hello ";//创建String对象,并赋值
String s2="java";
String s;
int count=0;//count用于计数
int index=0;//count用于计数
s=s1.concat(s2);//用字符串的concat方法连接两个字符串
System.out.println(s);
if(s1.equals(s2))//用equals函数来判断两个字符串是否相等
{
System.out.println("两个字符串相等");
}
else
{
System.out.println("两个字符串不相等");
}
while((index= s1.indexOf("l",index))!=-1)//用indexOf函数判断某一子字符串是否被包含在此字符串之中
{
//System.out.println(index);
index = index + "l".length();
count++;
}
if(count!=0)//用count的次数是否为0来判断是否存在
{
String s3=s.replace('l', 'n'); //用replace函数替换,如果要替换的字符不存在,则返回的还是原字符串
System.out.println("某一子字符串被包含在此字符串之中,包含的次数为:"+count);
System.out.println("替换之后的字符串为:"+s3);
}
else
{
System.out.println("某一子字符串不被包含在此字符串之中");
}
}
}
运行效果图
