String型字符串
定义方式
//二段式
String str0;
str0 = new String("Hello, World!");
// 使用字符串字面值定义一个String变量
String str1 = "Hello, World!";
// 使用String构造函数定义一个String变量
String str2 = new String("Hello, World!");注意
第二种方法和第三种方法所储存的方式不一样,所以二者即使字符串内容一致,但是使用==运算符判断时候还是false结果。
例子
package ch05;
public class ch055 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1=new String("aaaa");
String s2="aaaa";
String str;
str = new String("aaaa");
System.out.println(s1==s2);
System.out.println(str==s1);
String s3="aaaa";
System.out.println(s2==s3);
String s4="aaa"+"a";
System.out.println(s4==s3);
String s5="aa";
s5=s5+"aa";
System.out.println(s4==s5);
}
}String类常用方法
equals
equals()方法用于比较两个字符串的内容是否相等
package ch05;
public class ch055 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1=new String("aaaa");
String str;
str = new String("aaaa");
String s2 =("aaaa");
if(str.equals(s2)){
System.out.println("YES");
}
if(str.equals(s1)){
System.out.println("YES");
}
}
}substring与charAt
在Java中,substring()和charAt()是用于处理字符串的常用方法,它们有不同的作用:
substring(int beginIndex, int endIndex):substring()方法用于从原始字符串中提取子串。它接受两个参数,起始索引(beginIndex)和结束索引(endIndex),返回从beginIndex到endIndex-1之间的子字符串。charAt(int index):charAt()方法用于获取字符串中指定位置的字符。它接受一个整数参数index,表示要获取的字符在字符串中的位置,返回该位置上的字符。
package ch05;
public class ch055 {
public static void main(String[] args) {
String number =new String ("12345678910");
System.out.println("" + number.charAt(0) + number.charAt(1) + number.charAt(2) + "****" + number.charAt(7) + number.charAt(8) + number.charAt(9) + number.charAt(10));
//或者
System.out.println(number.substring(0, 3)+"****"+number.substring(7, 11));
}
}实践
判断字符串是否为回文
package ch05;
public class ch055 {
public static void main(String[] args) {
String hui =new String("123321");
String newStr="";
String sub;
for(int i=0;i<hui.length();i++)
{
sub=hui.substring(i, i+1);
newStr=sub+newStr;
}
if(hui.equals(newStr)) System.out.println("YES");
}
}正则表达式
在Java中,正则表达式是用于匹配、搜索和替换文本的强大工具。以下是Java中正则表达式的主要使用方法:
Pattern 类和 Matcher 类
Pattern类表示编译后的正则表达式模式,Matcher类用于对输入字符串进行匹配操作。
String text = "Hello, world!";
String pattern = "(H\\w+)"; // 匹配以H开头的单词
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
if (m.find()) {
System.out.println("匹配到的结果: " + m.group(0));
}常用方法
matches(String regex): 检查整个字符串是否匹配给定的正则表达式。
split(String regex): 使用给定的正则表达式拆分输入的字符串。
replaceFirst(String regex, String replacement) 和 replaceAll(String regex, String replacement): 替换字符串中与正则表达式匹配的部分。
String text = "apple,banana,orange";
String[] fruits = text.split(",");
for (String fruit : fruits) {
System.out.println(fruit);
}
String text2 = "I love apple, I eat apple everyday.";
String result = text2.replaceAll("apple", "banana");
System.out.println(result);常见的正则表达式符号
.: 匹配任何字符
*: 匹配零个或多个前面的元素
+: 匹配一个或多个前面的元素
[]: 匹配括号内的任意一个字符
^ 和 $: 匹配字符串的开始和结束
以上是Java中正则表达式的一些基本用法和方法,通过灵活运用正则表达式,可以实现强大的文本处理功能
粤公网安备44080202000201号