Java 字符串实例

字符串比较

以下实例中我们通过字符串函数 compareTo (string) ,compareToIgnoreCase(String) 及 compareTo(object string) 来比较两个字符串,并返回字符串中第一个字母ASCII的差值。

实例代码如下:

public class StringCompareEmp{
   public static void main(String args[]){
      String str = "Hello World";
      String anotherString = "hello world";
      Object objStr = str;
 
      System.out.println( str.compareTo(anotherString) );
      System.out.println( str.compareToIgnoreCase(anotherString) );  //忽略大小写
      System.out.println( str.compareTo(objStr.toString()));
   }
}
字符串比较

以上代码实例输出结果为:

result

 

查找字符串最后一次出现的位置

以下实例中我们通过字符串函数 strOrig.lastIndexOf(Stringname) 来查找子字符串 Stringname 在 strOrig 出现的位置:

实例代码如下:

public class SearchlastString {
   public static void main(String[] args) {
      String strOrig = "Hello world ,Hello Runoob";
      int lastIndex = strOrig.lastIndexOf("Runoob");
      if(lastIndex == - 1){
         System.out.println("没有找到字符串 Runoob");
      }else{
         System.out.println("Runoob 字符串最后出现的位置: "+ lastIndex);
      }
   }
}
lastIndexOf函数

以上代码实例输出结果为:

Runoob 字符串最后出现的位置: 19
View Code

 

删除字符串中的一个字符

以下实例中我们通过字符串函数 substring() 函数来删除字符串中的一个字符,我们将功能封装在 removeCharAt 函数中。

实例代码如下:

package com.feng;

public class Test {

    public static void main(String[] args) {
        String str = "My name is Mr.Feng";
        System.out.println("删除后的数据为:"+removeStr(str,3));
        
        

    }
    public static String removeStr(String str,int pos){
        return str.substring(0,pos)+str.substring(pos+1);
    }

}
substring 应用

以上代码实例输出结果为:

删除后的数据为:My ame is Mr.Feng
View Code

字符串替换

如何使用java替换字符串中的字符呢?

以下实例中我们使用 java String 类的 replace 方法来替换字符串中的字符:

package com.feng;

public class Test {

    public static void main(String[] args) {
        String str = "The god is a girl";
        
        System.out.println(str.replace("T","F"));
        System.out.println(str.replaceFirst("The", "That"));
        System.out.println(str.replaceAll("is", "are"));
        
        

    }
    
}
replace 函数

以上代码实例输出结果为:

Fhe god is a girl
That god is a girl
The god are a girl
View Code

 

字符串反转

以下实例演示了如何使用 Java 的反转函数 reverse() 将字符串反转:

package com.feng;

public class Test {

    public static void main(String[] args) {
        String str = "book";
        String reverse = new StringBuffer(str).reverse().toString();
        
        System.out.println("反转前:"+str);
        System.out.println("反转后"+reverse);
        

    }
    
}
StringBuffer

以上代码实例输出结果为:

反转前:book
反转后koob
View Code

 

字符串搜索

以下实例使用了 String 类的 indexOf() 方法在字符串中查找子字符串出现的位置,如果存在返回字符串出现的位置(第一位为0),如果不存在返回 -1:

package com.feng;

public class Test {

    public static void main(String[] args) {
        String str = "My name is Angel";
        int index = str.indexOf("name");
        if(index==-1){
            System.out.println("单词不存在");
        }else{
            System.out.println("单词位置为"+index);
        }
        

    }
    
}
indexOf

以上代码实例输出结果为:

单词位置为3
View Code

 

字符串分割

以下实例使用了 split(string) 方法通过指定分隔符将字符串分割为数组:

package com.feng;

public class Test {

    public static void main(String[] args) {
        String str1 = "www-cnblogs-Mr-Feng";
        String sp = "-";
        String[] temp = str1.split(sp);
        for(int i=0;i<temp.length;i++){
            System.out.println(temp[i]);
        }
        
        System.out.println("---------------------------------------------------------");
        
        String str2 = "www.cnblogs.Mr.Feng";
        String sp2 = "\\.";
        String [] temp2 = str2.split(sp2);
        for(String x:temp2){
            System.out.println(x);
        }
        

    }
    
}
split

 以上代码实例输出结果为:

www
cnblogs
Mr
Feng
---------------------------------------------------------
www
cnblogs
Mr
Feng
View Code

 

字符串小写转大写

以下实例使用了 String toUpperCase() 方法将字符串从小写转为大写:

package com.feng;

public class Test {

    public static void main(String[] args) {
        String str1 = "www,cnblogs,Mr.Feng";
        String str2 = str1.toUpperCase();
        System.out.println(str2);

    }
    
}
toUpperCase()

 

测试两个字符串区域是否相等

以下实例使用了 regionMatches() 方法测试两个字符串区域是否相等:

package com.feng;

public class Test {

    public static void main(String[] args) {
          String first_str = "Welcome to Microsoft";
          String second_str = "I work with microsoft";
          boolean match1 = first_str.
          regionMatches(11, second_str, 12, 9);
          boolean match2 = first_str.
          regionMatches(true, 11, second_str, 12, 9); //第一个参数 true 表示忽略大小写区别
          System.out.println("区分大小写返回值:" + match1);
          System.out.println("不区分大小写返回值:" + match2);

    }
    
}
regionMatches()

first_str.regionMatches(11, second_str, 12, 9) 表示将 first_str 字符串从第11个字符"M"开始和 second_str 字符串的第12个字符"M"开始逐个比较,共比较 9 对字符,由于字符串区分大小写,所以结果为false。

如果设置第一个参数为 true ,则表示忽略大小写区别,所以返回 true。

以上代码实例输出结果为:

区分大小写返回值:false 
不区分大小写返回值:true
View Code

 

字符串性能比较测试

以下实例演示了通过两种方式创建字符串,并测试其性能:
package com.feng;

public class Test {

    public static void main(String[] args) {
          long startTime = System.currentTimeMillis();
          for(int i=0;i<50000;i++){
              String s1 = "hello";
              String s2 = "hello";
          }
          long endTime = System.currentTimeMillis();
          System.out.println(endTime-startTime);
          
          System.out.println("-------------------------------------------");
          long startTime1 = System.currentTimeMillis();
          for(int i=0;i<50000;i++){
              String s1 = new String("hello");
              String s2 =  new String("hello");
          }
          long endTime1 = System.currentTimeMillis();
          System.out.println(endTime1-startTime1);
    }
    
}
View Code

以上代码实例输出结果为:

3
-------------------------------------------
8
View Code

 

字符串优化

以下实例演示了通过 String.intern() 方法来优化字符串:
public class StringOptimization {
    public static void main(String[] args){
        String variables[] = new String[50000];      
        for( int i=0;i <50000;i++){
            variables[i] = "s"+i;
        }
        long startTime0 = System.currentTimeMillis();
        for(int i=0;i<50000;i++){
            variables[i] = "hello";
        }
        long endTime0 = System.currentTimeMillis();
        System.out.println("直接使用字符串: "+ (endTime0 - startTime0)  + " ms" );
        long startTime1 = System.currentTimeMillis();
            for(int i=0;i<50000;i++){
            variables[i] = new String("hello");
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("使用 new 关键字:" + (endTime1 - startTime1) + " ms");
        long startTime2 = System.currentTimeMillis();
        for(int i=0;i<50000;i++){
            variables[i] = new String("hello");
            variables[i] = variables[i].intern();          
        }
        long endTime2 = System.currentTimeMillis();
        System.out.println("使用字符串对象的 intern() 方法: " 
        + (endTime2 - startTime2)
        + " ms");
    }
}
View Code

以上代码实例输出结果为:

直接使用字符串: 3 ms
使用 new 关键字:5 ms
使用字符串对象的 intern() 方法: 10 ms
View Code

 

字符串格式化

以下实例演示了通过 format() 方法来格式化字符串,还可以指定地区来格式化:

import java.util.*;
 
public class StringFormat {
    public static void main(String[] args){
        double e = Math.E;
        System.out.format("%f%n", e);
        System.out.format(Locale.CHINA  , "%-10.4f%n%n", e);  //指定本地为中国(CHINA)
    }
}
View Code

以上代码实例输出结果为:

2.718282
2.7183  
View Code

 

连接字符串

"+" 操作符和StringBuffer.append() 方法来连接字符串,并比较其性能:

public class StringConcatenate {
    public static void main(String[] args){
        long startTime = System.currentTimeMillis();
        for(int i=0;i<5000;i++){
            String result = "This is"
            + "testing the"
            + "difference"+ "between"
            + "String"+ "and"+ "StringBuffer";
        }
        long endTime = System.currentTimeMillis();
        System.out.println("字符串连接" 
        + " - 使用 + 操作符 : " 
        + (endTime - startTime)+ " ms");
        long startTime1 = System.currentTimeMillis();
        for(int i=0;i<5000;i++){
            StringBuffer result = new StringBuffer();
            result.append("This is");
            result.append("testing the");
            result.append("difference");
            result.append("between");
            result.append("String");
            result.append("and");
            result.append("StringBuffer");
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("字符串连接" 
        + " - 使用 StringBuffer : "
        + (endTime1 - startTime1)+ " ms");
    }
}
View Code

以上代码实例输出结果为:

字符串连接 - 使用 + 操作符 : 0 ms
字符串连接 - 使用 StringBuffer : 6 ms
View Code

 

转载于:https://www.cnblogs.com/Mr-Feng/p/11371666.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值