Java常用字符串方法小结
发布于 2020-12-30|
字符串变量是Java与C语言的一大不同之处。Java之中的 String 类和 Stringbuffer 类提供了大量的对字符串操作的方法。String 类适合处理较小的字符串,而Stringbuffer类适合处理大量字符串
下面是对字符串操作的代码小总结。大部分是String类的 操作方法,需要的朋友可以参考下
```java
public class StudyString {
public static void main(String[] ergs){
//字符串的声明与赋值
String name = "蔡宇飞";
String hisname = new String ("小明");
System.out.println(name+"和"+hisname+"是好朋友");
//字符串基本操作
//获取字符串的长度
//字符串名.length() 返回字符的个数
String hello = "hello world!";
int length = hello.length();
System.out.println(hello+"的长度是"+length);
//字符串连接
//String类提供的concat()方法
//字符串1.concat(字符串2) 返回值是一个字符串
String twoname = name.concat(hisname);
System.out.println(twoname);
//字符串比较
//String提供的equals()方法,返回值为boolean类型。两个字符串中每个字符完全一致时才为turn.否则为false
//字符串1.equals(字符串2)
String str1 = "fuck";
String str2 = "FUCK";
if (str1.equals(str2))
System.out.println("相同");
else
System.out.println("不同");
//String还提供了equalsIgnoreCase()方法,这个与上面的区别是不区分字母的大小写。返回值同样为boolean类型
//字符串1.equalsIgnoreCase(字符串2)
if(str1.equalsIgnoreCase(str2))
System.out.println("相同");
else
System.out.println("不同");
//字符串截取
//从字符串中截取一部分作为新的字符串,String类提供的substring来实现
//字符串.substring (开始位置); 或者 字符串.substring (开始位置,结束位置);
//第一种是从开始位置直到结束,第二种从开始位置到结束位置.
String my ="my name is caiyufei,I love Java and Python.";
String love =my.substring(20);
String myname = my.substring(11, 19);
System.out.println(love);
System.out.println(myname);
//字符串查找
//在一个字符串中查找另一个字符串,String类提供了indexOf方法来实现
//字符串1.indexOf(字符串2) 或 字符串1.indexOf(字符串2,开始位置)
int lovenum = my.indexOf(love);
int mynamenum = my.indexOf(myname);
System.out.println(lovenum);
System.out.println(mynamenum);
//字符串替换
//用一个新字符去替换字符串中指定的所有字符 String类提供了replace方法实现这种替换
//字符串1.replance(被替换字符,替换字符)
char I_ = 'I';
char m_ = 'M';
System.out.println(love.replace(I_, m_)); //M love Java and Python.
//字符串与字符数组
//将字符数组作为构造函数的参数直接转换成字符串
char [] helloArray = {'h','e','l','l','o'};
String helloString = new String (helloArray);
System.out.println(helloString);
//将字符串转为字符数组
//toCharArray()方法
char [] Array = helloString.toCharArray();
for (int i = 0;i原文地址: http://blog.csdn.net/m0_37591251/article/details/70147146