java中string字符串操作


在网上顺手牵了2篇文章,都是关于String类的方法。


本文章分享一篇关于java中string字符串操作程序,包括了拆分,替换,查找,等操作,有需要的朋友可以参考一下本文章。


String的两种实例化方法

  String本身是一个类,在String类中定义了如下的构造方法:

    public String (String original)

  可以接收一个String类的对象,并重新实例化String对象,除了此方法之外,String还可以采用直接赋值的方式进行对象的实例化。

 代码如下 复制代码
public class StringDemo01{
  public static void main(String args[]){
   String str1 = "hello" ; //使用直接赋值的方式完成
  String str2 = new String("WORLD") ; //通过构造方法完成
  System.out.println(str1 + str2) ; //进行字符串的连接操作
 }
 }
 

  此时,两个String类型的对象都实例化。

 

2、String的比较方式

  现有如下一道程序,观察String的比较问题:

 代码如下 复制代码

public class StringDemo01{
  public static void main(String args[]){
   String str1 = "hello" ; //使用直接赋值的方式完成
  String str2 = new String("hello") ; //通过构造方法完成
  String str3 = str2 ; //通过构造方法完成
  System.out.println("str1 == str2 --> " + (str1 == str2)) ; //false
   System.out.println("str1 == str3 --> " + (str1 == str3)) ; //false
   System.out.println("str2 == str3 --> " + (str2 == str3)) ; //true
  }
 }
 

从内存关系来分析结果:


得到一个结果,实际上对于“==”,比较的是两个对象的地址是否相等,具体来讲实际上比较的是地址的值,因为地址是以数值的形式存在的。

  但是现在真正要比较的不是地址的值,而是两个字符串的内容,所以现在就需要使用String类中的equals()方法完成比较,此方法定义如下:

    public boolean equals(String str)

  比如:使用equals()修改程序

 代码如下 复制代码
public class StringDemo01{
  public static void main(String args[]){
   String str1 = "hello" ; //使用直接赋值的方式完成
  String str2 = new String("hello") ; //通过构造方法完成
  String str3 = str2 ; //通过构造方法完成
  System.out.println("str1 equals str2 --> " + str1.equals(str2)) ; //true
   System.out.println("str1 equals str3 --> " + str1.equals(str3)) ; //true
   System.out.println("str2 equals str3 --> " + str2.equals(str3)) ; //true
  }
 }
  

此时,因为三个字符串的内容完全相等,所以此时equals用于比较字符串内容。

 

3、一个字符串实际上就是String的匿名对象

  一个字符串是使用“"”括起来的,那么一个字符串的常量实际上本身就属于String的一个匿名对象。

 代码如下 复制代码
public class StringDemo01{
  public static void main(String args[]){
   String str1 = "hello" ; //使用直接赋值的方式完成
  System.out.println("hello".equals(str1)) ; //true
  }
 }
 

  

 

4、String的两种实例化方式的区别

  内存图形表示:

    String str1 = "hello" ;


    

    现在在堆内存空间中,只开辟了有一个空间,不会产生多余的内容。

 

  现在使用关键字new的方式:

    String str2 = new String("hello") ;


    可以发现,程序开辟了两个空间,与直接赋值相比,肯定使用直接赋值的方式方便,所以在开发中绝对不能使用关键字new调用String(String original)的构造方法。

    而且,如果使用直接赋值的方式也可以减少堆内存的开销。


  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str1 = "hello" ; //使用直接赋值的方式完成
  String str2 = "hello" ; //使用直接赋值的方式完成
  String str3 = "hello" ; //使用直接赋值的方式完成
  System.out.println("str1 == str2 --> " + (str1 == str2)) ; //true
  System.out.println("str1 == str3 --> " + (str1 == str3)) ; //true
  System.out.println("str2 == str3 --> " + (str2 == str3)) ; //true
 }
}

 
  

     实际上,以上的三个对象表示的都是同一个空间的引用,因为对于String来讲,使用直接赋值的方式,会在字符串池中保存内容。如果之后再声明字符串的时候发现内容相同,则不会重新开辟空间,而是从内存池中取出数据继续使用。


 

5、字符串的内容一旦声明之后则无法修改


  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "hello" ; //使用直接赋值的方式完成
  str += " world" ;
  System.out.println(str) ;
 }
}

 
  

   虽然最终输出的结果改变了,但是字符串的内容没有改变:


  实际上来讲,字符串变量的改变是改变的内存空间地址的指向,而本身的字符串内容没有任何变化。所以,在开发中一下的操作代码绝对要避免:


  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "hello" ; //使用直接赋值的方式完成
  for (int i = 0; i < 100; i++){
   str += i ;
  }
  System.out.println(str) ;
 }
}

 
  

     以上的操作代码要不断的断开已有的连接,指向新连接100次,整体代码的性能及其低,所以遇到此类绝对不要使用。
6、String的常用操作方法
  (1)、字符与字符串
    在各个语言中实际上个一个字符串就表示一组字符。所以在String类中提供了以下的方法操作字符与字符串间的转换关系:
      根据字符串中的索引找到指定位置的字符:public char charAt(int index)
      将字符串变为字符数组:public char[] toCharArray()
      将字符数组变为字符串:
        将全部的字符数组变为String类型:public String(char[] value)
        将部分的字符数组变为String类型:public String(char[] value, int offset, int count)
 
  例1:取出字符串中指定位置的字符

  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "hello" ;
  char c = str.charAt(1) ;
  System.out.println(c) ;
 }
}

 
  

   
  例2:字符串 <--> 字符数组

  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "hello world!!!" ;
  char c[] = str.toCharArray() ; //将字符串变为字符数组
  for (int i=0; i<c.length; i++){
   System.out.print(c[i] + "、") ;
  }
  String str1 = new String(c) ; //将全部的字符数组重新变为String
  String str2 = new String(c, 0 ,5) ; //将0~5的字符数组重新变为String
  System.out.println() ;
  System.out.println(str1) ;
  System.out.println(str2) ;
 }
}

 
  

   
  (2)、字节与字符串
    与字符数组的操作一致,一个字符串也可以变为字节数组,一个字节数组也可以变为字符串:
      String --> 字节数组:public bytr[] getBytes()
      字节数组 --> String:
        全部转换:public String(byte[] bytes)
        部分转换:public String(byte[] bytes, int offset, int length)
 
  例:字节数组 --> String

  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "hello world!!!" ;
  byte c[] = str.getBytes() ; //将字符串变为byte数组
  String str1 = new String(c) ; //将全部的byte数组重新变为String
  String str2 = new String(c, 0 ,5) ; //将0~5的byte数组重新变为String
  System.out.println(str1) ;
  System.out.println(str2) ;
 }
}

  

 
  

   (3)、判断是否以指定的字符串开头或结尾
    判断是否以指定的字符串开头:public boolean sttsWith(String prefix)
    判断是否以指定的字符串结尾:public boolean endsWith(String suffix)
  例:验证操作

  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "**hello world!!!##" ;
  System.out.println(str.startsWith("**")) ; //true
  System.out.println(str.endsWith("##")) ; //true
 }
}

  

 
  

   (4)、替换操作
    使用以下的方法可以完成替换的操作:
      public String replaceAll(String regex, String replacement)
  例:替换内容

  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "hello world" ;
  String newStr = str.replaceAll("l", "x") ; //将全部的l用x替换
  System.out.println(newStr) ;
 }
}

 

 
  

  
  (5)、字符串截取
    使用以下两个方法可以完成字符串的截取操作:
      全部截取:public String substring(int beginIndex)
      部分截取:public String substring(int beginIndex, int endIndex)
  例:验证操作

  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "hello world" ;
  String sub1 = str.substring(6) ; //world
  String sub2 = str.substring(0, 4) ; //hello
  System.out.println(sub1) ;
  System.out.println(sub2) ;
 }
}

 

 
  

  
  (6)、字符串的拆分操作
    可以将字符串按照指定的内容进行拆分操作:
      public String[] split(string regex)
  例:拆分字符串

  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "hello world" ;
  String s[] = str.split(" ") ; //按照空格拆分
  for (String st:s ){
   System.out.println(st) ;
  }
 }
}

  

 
  

   (7)、字符串查找
    如果需要在一个字符串中查找是否存在指定的内容,可以使用以下的两个方法:
      取得指定字符串的位置:public int indexOf(String str)
        此方法返回int型数据,如果查找到了则返回位置,查找不到,返回-1
      从指定位置开始查找:public int indexOf(String str, int fromIndex)
      直接查找:public boolean contains(String s)
  例1:查找操作

  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "hello world" ;
  System.out.println(str.contains("hello")) ; //true
  System.out.println(str.contains("hl")) ; //false
 }
}

 
  

   
  例2:查找位置

  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "hello world" ;
  System.out.println(str.indexOf("hello")) ;
  System.out.println(str.indexOf("hl")) ;
  if (str.indexOf("hello") != -1){
   System.out.println("查找到了所需要的内容") ;
  }
 }
}

  

 
  

   例3:指定查找的开始位置

  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "hello world" ;
  System.out.println(str.indexOf("h" ,5)) ; //true
 }
}

  

 
  

   (8)、字符串的其他操作
    去掉左右空格:public String trim()
    取得字符串长度:public int length()
    转大写:public String toUpperCase()
    转小写:public String toLowerCase()
  例:验证操作

  
   代码如下
  复制代码
  

  
  public class StringDemo01{
 public static void main(String args[]){
  String str = "   hello world   " ;
  System.out.println(str.trim()) ; //去掉空格
  System.out.println(str.trim().toUpperCase()) ; //转换为大写
  System.out.println(str.trim().length()) ; //求出去掉空格后的字符串的长的
 }
}
 


更多详细内容请查看:http://www.111cn.net/jsp/Java/41521.htm





String : 字符串类型

一、构造函数
     String(byte[ ] bytes):通过byte数组构造字符串对象
     String(char[ ] value):通过char数组构造字符串对象
     String(Sting original):构造一个original副本。即:拷贝一个original
     String(StringBuffer buffer):通过StringBuffer数组构造字符串对象。  
例如:
      byte[] b = {'a','b','c','d','e','f','g','h','i','j'};
      char[] c = {'0','1','2','3','4','5','6','7','8','9'};
      String sb = new String(b);                 //abcdefghij
      String sb_sub = new String(b,3,2);     //de
      String sc = new String(c);                  //0123456789
      String sc_sub = new String(c,3,2);    //34
      String sb_copy = new String(sb);       //abcdefghij  
      System.out.println("sb:"+sb);
      System.out.println("sb_sub:"+sb_sub);
      System.out.println("sc:"+sc);
      System.out.println("sc_sub:"+sc_sub);
      System.out.println("sb_copy:"+sb_copy);
      输出结果sb:abcdefghij
                      sb_sub:de
                       sc:0123456789
                        sc_sub:34
                        sb_copy:abcdefghij

二、方法:

     说明:①、所有方法均为public。
           ②、书写格式: [修饰符] <返回类型><方法名([参数列表])>

      例如:static int parseInt(String s)
      表示此方法(parseInt)为类方法(static),返回类型为(int),方法所需要为String类型。

1. char charAt(int index)取字符串中的某一个字符,其中的参数index指的是字符串中序数。字符串的序数从0开始到length()-1 。
    例如:String s = new String("abcdefghijklmnopqrstuvwxyz");
          System.out.println("s.charAt(5): " + s.charAt(5) );
          结果为: s.charAt(5): f
2. int compareTo(String anotherString)当前String对象与anotherString比较相等关系返回0不相等时,从两个字符串第0个字符开始比较,返回第一个不相等的字符差,另一种情况,较长字符串的前面部分恰巧是较短的字符串,返回它们的长度差。
3. int compareTo(Object o) :如果o是String对象,和2的功能一样;否则抛出ClassCastException异常。
    例如:String s1 = new String("abcdefghijklmn");
            String s2 = new String("abcdefghij");
           String s3 = new String("abcdefghijalmn");
           System.out.println("s1.compareTo(s2): " + s1.compareTo(s2) ); //返回长度差
           System.out.println("s1.compareTo(s3): " + s1.compareTo(s3) ); //返回'k'-'a'的差
           结果为:s1.compareTo(s2): 4
                       s1.compareTo(s3): 10
4. String concat(String str)将该String对象与str连接在一起。
5. boolean contentEquals(StringBuffer sb) 将该String对象与StringBuffer对象sb进行比较。
6. static String copyValueOf(char[] data)
7. static String copyValueOf(char[] data, int offset, int count) :这两个方法将char数组转换成String,与其中一个构造函数类似。
8. boolean endsWith(String suffix)该String对象是否以suffix结尾
    例如:String s1 = new String("abcdefghij");
           String s2 = new String("ghij");
           System.out.println("s1.endsWith(s2): " + s1.endsWith(s2) );
           结果为:s1.endsWith(s2): true
9. boolean equals(Object anObject)当anObject不为空并且与当前String对象一样,返回true;否则,返回false
10. byte[] getBytes()将该String对象转换成byte数组
11. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)该方法将字符串拷贝到字符数组中。其中,srcBegin为拷贝的起始位置、srcEnd为拷贝的结束位置、字符串数值dst为目标字符数组、dstBegin为目标字符数组的拷贝起始位置。
     例如:char[] s1 = {'I',' ','l','o','v','e',' ','h','e','r','!'};//s1=I love her!
           String s2 = new String("you!"); s2.getChars(0,3,s1,7); //s1=I love you!
           System.out.println( s1 );
           结果为:I love you!
12. int hashCode()返回当前字符的哈希表码
13. int indexOf(int ch)只找第一个匹配字符位置
14. int indexOf(int ch, int fromIndex)fromIndex开始找第一个匹配字符位置
15. int indexOf(String str)只找第一个匹配字符串位置
16. int indexOf(String str, int fromIndex)从fromIndex开始找第一个匹配字符串位置
      例如:String s = new String("write once, run anywhere!");
              String ss = new String("run");
              System.out.println("s.indexOf('r'): " + s.indexOf('r') );
              System.out.println("s.indexOf('r',2): " + s.indexOf('r',2) );
              System.out.println("s.indexOf(ss): " + s.indexOf(ss) );
              结果为:s.indexOf('r'): 1
                      s.indexOf('r',2): 12
                      s.indexOf(ss): 12
17. int lastIndexOf(int ch)
18. int lastIndexOf(int ch, int fromIndex)
19. int lastIndexOf(String str)
20. int lastIndexOf(String str, int fromIndex) 以上四个方法与13、14、15、16类似,不同的是:找后一个匹配的内容
public class CompareToDemo {
      public static void main (String[] args) {
           String s1 = new String("acbdebfg");
     
           System.out.println(s1.lastIndexOf((int)'b',7));
     }
}
运行结果5
       (其中fromIndex的参数为 7,是从字符串acbdebfg的最后一个字符g开始往前数的位数。既是从字符c开始匹配,寻找最后一个匹配b的位置。所以结果为 5


21. int length()返回当前字符串长度
22. String replace(char oldChar, char newChar)将字符号串中第一个oldChar替换成newChar
23. boolean startsWith(String prefix)该String对象是否以prefix开始
24. boolean startsWith(String prefix, int toffset)该String对象从toffset位置算起,是否以prefix开始
     例如:String s = new String("write once, run anywhere!");
             String ss = new String("write");
             String sss = new String("once");
             System.out.println("s.startsWith(ss): " + s.startsWith(ss) );
             System.out.println("s.startsWith(sss,6): " + s.startsWith(sss,6) );
             结果为:s.startsWith(ss): true
                     s.startsWith(sss,6): true
25. String substring(int beginIndex) 取从beginIndex位置开始到结束的子字符串
26.String substring(int beginIndex, int endIndex)取从beginIndex位置开始到endIndex位置的子字符串
27. char[ ] toCharArray()将该String对象转换成char数组
28. String toLowerCase()将字符串转换成小写
29. String toUpperCase() :将字符串转换成大写。
     例如:String s = new String("java.lang.Class String");
             System.out.println("s.toUpperCase(): " + s.toUpperCase() );
             System.out.println("s.toLowerCase(): " + s.toLowerCase() );
             结果为:s.toUpperCase(): JAVA.LANG.CLASS STRING
                  s.toLowerCase(): java.lang.class string
30. static String valueOf(boolean b)
31. static String valueOf(char c)
32. static String valueOf(char[] data)
33. static String valueOf(char[] data, int offset, int count)
34. static String valueOf(double d)
35. static String valueOf(float f)
36. static String valueOf(int i)
37. static String valueOf(long l)
38. static String valueOf(Object obj)
     以上方法用于将各种不同类型转换成Java字符型。这些都是类方法。

 

 

Java中String类的常用方法:

public char charAt(int index)

返回字符串中第index个字符;
public int length()
返回字符串的长度;
public int indexOf(String str)
返回字符串中第一次出现str的位置;
public int indexOf(String str,int fromIndex)
返回字符串从fromIndex开始第一次出现str的位置;
public boolean equalsIgnoreCase(String another)
比较字符串与another是否一样(忽略大小写);
public String replace(char oldchar,char newChar)
在字符串中用newChar字符替换oldChar字符
public boolean startsWith(String prefix)
判断字符串是否以prefix字符串开头;
public boolean endsWith(String suffix)
判断一个字符串是否以suffix字符串结尾;
public String toUpperCase()
返回一个字符串为该字符串的大写形式;
public String toLowerCase()
返回一个字符串为该字符串的小写形式
public String substring(int beginIndex)
返回该字符串从beginIndex开始到结尾的子字符串;
public String substring(int beginIndex,int endIndex)
返回该字符串从beginIndex开始到endsIndex结尾的子字符串
public String trim()
返回该字符串去掉开头和结尾空格后的字符串
public String[] split(String regex)
将一个字符串按照指定的分隔符分隔,返回分隔后的字符串数组
实例:  
public class SplitDemo{
     public static void main (String[] args) {

             String date = "2008/09/10";
            String[ ] dateAfterSplit= new String[3];
            dateAfterSplit=date.split("/");         //以“/作为分隔符来分割date字符串,并把结果放入3个字符串中。

            for(int i=0;i<dateAfterSplit.length;i++)
                       System.out.print(dateAfterSplit[i]+" ");
      }
}

运行结果2008 09 10          //结果为分割后的3个字符串

实例:
TestString1.java:
程序代码
public class TestString1
{
    public static void main(String args[]) {
        String s1 = "Hello World" ;
        String s2 = "hello world" ;
        System.out.println(s1.charAt(1)) ;
        System.out.println(s2.length()) ;
        System.out.println(s1.indexOf("World")) ;
        System.out.println(s2.indexOf("World")) ;
        System.out.println(s1.equals(s2)) ;
        System.out.println(s1.equalsIgnoreCase(s2)) ;

        String s = "我是J2EE程序员" ;
        String sr = s.replace('我','你') ;
        System.out.println(sr) ;
    }
}

TestString2.java:
程序代码

public class TestString2
{
    public static void main(String args[]) {
        String s = "Welcome to Java World!" ;
        String s2 = "   magci   " ;
        System.out.println(s.startsWith("Welcome")) ;
        System.out.println(s.endsWith("World")) ;
        String sL = s.toLowerCase() ;
        String sU = s.toUpperCase() ;
        System.out.println(sL) ;
        System.out.println(sU) ;
        String subS = s.substring(11) ;
        System.out.println(subS) ;
        String s1NoSp = s2.trim() ;
        System.out.println(s1NoSp) ;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值