Java字符串实例

如何比较两个字符串?

package com.xyc.springInstance;

/**
 * 
 * @ClassName:  StringCompareEmp   
 * @Description:如何比较两个字符串?
 * @author: xyc 
 * @date:   2017年2月9日 下午2:14:17   
 *
 */
public class StringCompareEmp {
    
    public static void main(String args[]) {
        String str = "Hello World";
        String anotherString = "hello world";
        Object objStr = str;

        
        //compareTo:按字典顺序比较两个字符串
        //如果该参数字符串 等于 此字符串返回值0,
        //如果该字符串是按字典顺序比字符串参数 少,返回值小于0,
        //如果这个字符串是按字典顺序比字符串参数 大 则返回一个大于0的值。
        System.out.println(str.compareTo(anotherString));
        
        //按字典顺序比较两个字符串,不区分大小写的差异。
        //此方法返回一个负整数,零或正整数;如果指定字符串大于,等于或小于这个字符串(忽略大小写)。
        System.out.println(str.compareToIgnoreCase(anotherString));
        
        
        System.out.println(str.compareTo(objStr.toString()));
    }
}
View Code

 上面的代码示例将产生以下结果

-32
0
0

  

如何搜索一个子字符串的最后一个位置? 

package com.xyc.springInstance;

/**
 * 
 * @ClassName: SearchlastString
 * @Description:如何搜索一个子字符串的最后一个位置?
 * @author: xyc
 * @date: 2017年2月9日 下午3:06:41
 *
 */
public class SearchlastString {

    public static void main(String[] args) {
        
        String strOrig = "Hello world ,Hello Reader";
        
        //lastIndexOf方法返回该字符串指定字符最后一次出现处的索引。
        //如果该字符没有找到,返回-1.
        //如果找到了  则返回该字符串在指定字符串中出现的位置
        int lastIndex = strOrig.lastIndexOf("Hello");
        
        if (lastIndex == -1) {
            System.out.println("Hello not found");
        } else {
            System.out.println("Last occurrence of Hello is at index "+ lastIndex);
        }
        
    }
}
View Code

 上面的代码示例将产生以下结果:

Last occurrence of Hello is at index 13

   

如何从一个字符串中删除特定字符?

package com.xyc.springInstance;

/**
 * 
 * @ClassName: Main
 * @Description:如何从一个字符串中删除特定字符?
 * @author: xyc
 * @date: 2017年2月9日 下午3:36:16
 *
 */
public class RemovePosition {

    public static void main(String args[]) {
        String str = "this is Java";
        //删除索引为3的字符
        System.out.println(removeCharAt(str, 3));
    }

    public static String removeCharAt(String s, int pos) {
        //java.lang.String.substring(int beginIndex, int endIndex) 方法返回一个新的字符串,它是此字符串的一个子字符串。
        //该子字符串从指定的beginIndex,并延伸到endIndex- 1处的字符索引。这个子串的长度为endIndex- beginIndex。
        
        //beginIndex -- 这是开始索引,包函这个值。
        //endIndex -- 这是最后的索引,不包函这个值。
        
        
        //java.lang.String.substring(int beginIndex) 方法返回一个新的字符串,它是此字符串的一个子字符串。
        //该字符串开头的字符指定索引处一直延伸到这个字符串的结尾。
        return s.substring(0, pos) + s.substring(pos + 1);
    }
}
View Code

 上面的代码示例将产生以下结果:

thi is Java

  

 如何通过另一个子字符串替另一个字符串?  

package com.xyc.springInstance;

/**
 * 
 * @ClassName:  StringReplaceEmp   
 * @Description:如何通过另一个子字符串替另一个字符串?  
 * @author: xyc 
 * @date:   2017年2月9日 下午4:17:29   
 *
 */
public class StringReplaceEmp{
    
   public static void main(String args[]){
       
      String str="Hello World";
      
      //java.lang.String.replace(char oldChar, char newChar) 方法返回通过用newChar更换oldChar所有出现在此字符串产生一个新的字符串。
      System.out.println( str.replace('H','W'));
      
      //java.lang.String.replaceFirst() 方法替换此字符串匹配给定的正则表达式与给定替换的第一个子字符串。
      System.out.println( str.replaceFirst("He", "Wa"));
      
      //java.lang.String.replaceAll() 方法替换此字符串匹配给定的正则表达式与给定替换每个子字符串。
      System.out.println( str.replaceAll("He", "Ha"));
      
   }
   
}
View Code

 上面的代码示例将产生以下结果:

Wello World
Wallo World
Hallo World

   

如何逆转/反转一个字符串? 

package com.xyc.springInstance;

/**
 * 
 * @ClassName:  StringReverseExample   
 * @Description:如何逆转/反转一个字符串?   
 * @author: xyc 
 * @date:   2017年2月9日 下午4:36:51   
 *
 */
public class StringReverseExample{
    
   public static void main(String[] args){
       
      String string="abcdef";
      
      String reverse = new StringBuffer(string).reverse().toString();
      
      System.out.println("String before reverse:"+string);
      System.out.println("String after reverse:"+reverse);
   }
   
}
View Code

上面的代码示例将产生以下结果:

String before reverse:abcdef
String after reverse:fedcba

  

如何在字符串中搜索一个单词?

package com.xyc.springInstance;

/**
 * 
 * @ClassName: SearchStringEmp
 * @Description:如何在字符串中搜索一个单词?
 * @author: xyc
 * @date: 2017年2月9日 下午4:53:31
 *
 */
public class SearchStringEmp {

    public static void main(String[] args) {
        String strOrig = "Hello readers";
        
        //indexOf返回该字符串指定字符第一次出现处的索引。
        int intIndex = strOrig.indexOf("Hello");
        if (intIndex == -1) {
            System.out.println("Hello not found");
        } else {
            System.out.println("Found Hello at index " + intIndex);
        }
    }

}
View Code

上面的代码示例将产生以下结果:

Found Hello at index 0

  

 如何将一个字符串分割成若干子字符串?

package com.xyc.springInstance;

/**
 * 
 * @ClassName:  JavaStringSplitEmp   
 * @Description:如何将一个字符串分割成若干子字符串?
 * @author: xyc 
 * @date:   2017年2月9日 下午4:58:43   
 *
 */
public class JavaStringSplitEmp {

    public static void main(String args[]){
        
      String str = "jan-feb-march";
      String[] temp;
      String delimeter = "-";
      temp = str.split(delimeter);
      
      for(int i =0; i < temp.length ; i++){
         System.out.println(temp[i]);
         System.out.println("");
         str = "jan1.feb1.march1";
         delimeter = "\\.";
         temp = str.split(delimeter);
      }
      
      for(int i =0; i < temp.length ; i++){
         System.out.println(temp[i]);
         System.out.println("");
         //根据delimeter分成2个字符串
         temp = str.split(delimeter,2);
         for(int j =0; j < temp.length ; j++){
            System.out.println(temp[i]);
         }
      }
      
   }
}
View Code

上面的代码示例将产生以下结果(略不太好理解,debug走):

jan

feb1

march1

jan1

jan1
jan1
feb1.march1

feb1.march1
feb1.march1

  

如何将字符串转全部换成大写? 

package com.xyc.springInstance;

/**
 * 
 * @ClassName:  StringToUpperCaseEmp   
 * @Description:如何将字符串转全部换成大写? 
 * @author: xyc 
 * @date:   2017年2月10日 上午8:36:09   
 *
 */
public class StringToUpperCaseEmp {
    
   public static void main(String[] args) {
       
      String str = "string abc touppercase ";
      //将一个字符串转换为大写使用String toUpperCase()方法完成。
      String strUpper = str.toUpperCase();
      
      System.out.println("Original String: " + str);
      System.out.println("String changed to upper case: "+ strUpper);
   }
   
}
View Code

上面的代码示例将产生以下结果:

Original String: string abc touppercase 
String changed to upper case: STRING ABC TOUPPERCASE 

  

如何在字符串中匹配区域 ? 

package com.xyc.springInstance;

/**
 * 
 * @ClassName:  StringRegionMatch   
 * @Description:如何在字符串中匹配区域 ?
 * @author: xyc 
 * @date:   2017年2月10日 上午9:01:43   
 *
 */
public class StringRegionMatch{
    
   public static void main(String[] args){
       
      String first_str = "Welcome to Microsoft";
      String second_str = "I work with Microsoft";
      
      //表示将first_str字符串从第11个字符“M”开始和s2字符串的第12个字符“M”开始逐个比较,共比较9对字符,并且区分大小写
      boolean match = first_str.regionMatches(11, second_str, 12, 9);
      
      System.out.println("first_str[11 -19] == "+ "second_str[12 - 21]:"+ match);
      
   }
}
View Code

上面的代码示例将产生以下结果:

first_str[11 -19] == second_str[12 - 21]:-true 

  

如何比较字符串创建的性能呢?

package com.xyc.springInstance;

/**
 * 
 * @ClassName:  StringComparePerformance   
 * @Description:如何比较字符串创建的性能呢?
 * @author: xyc 
 * @date:   2017年2月10日 上午9:15:00   
 *
 */
public class StringComparePerformance{
    
   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("Time taken for creation" + " of String literals : "+ (endTime - startTime) + " milli seconds" );       
      
      
      long startTime1 = System.currentTimeMillis();
      for(int i=0;i<50000;i++){
         String s3 = new String("hello");
         String s4 = new String("hello");
      }
      long endTime1 = System.currentTimeMillis();
      
      System.out.println("Time taken for creation"  + " of String objects : " + (endTime1 - startTime1)+ " milli seconds");
      
      
      
      //关于字符串String赋值,String a="123", 这种方式比String a = new String("123");效率高多了。
      //后者其实会创建两个对象。 "123"是一个常量池里的对象,new出来的对象是存放在内存堆中的,new出来的又是一个对象。
      
      //String a = "aaa";用这种方式的时候java首先在内存中寻找"aaa"字符串,如果有,就把aaa的地址给它 .如果没有则创建
      //String a = new String("aaa"); 是不管内存中有没有"aaa"  都开辟一块新内存保存它
      
      /*可以用以下方法验证下
      String a = "aaa";
      String b = "aaa";
      String c = new String("aaa");
      System.out.println(a==b);
      System.out.println(a==c);
                  结果应该是:
      true
      false*/
   }
}
View Code

上面的代码示例将产生以下结果:

Time taken for creation of String literals : 1 milli seconds
Time taken for creation of String objects : 9 milli seconds

  

如何优化字符串创建?  

package com.xyc.springInstance;

/**
 * 
 * @ClassName:  StringOptimization   
 * @Description: 如何优化字符串创建?
 * @author: xyc 
 * @date:   2017年2月10日 上午9:25:27   
 *
 */
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("Creation time" + " of String literals : "+ (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("Creation time of" + " String objects with 'new' key word : " + (endTime1 - startTime1)+ " ms");
          
          long startTime2 = System.currentTimeMillis();
          for(int i=0;i<50000;i++){
             variables[i] = new String("hello");
             //intern()此方法返回具有相同的内容正如这个字符串,但保证从字符串池中是唯一的。
             variables[i] = variables[i].intern();          
          }
          long endTime2 = System.currentTimeMillis();
          System.out.println("Creation time of" + " String objects with intern(): " + (endTime2 - startTime2)+ " ms");
       }
    }
View Code

上面的代码示例将产生以下结果。该结果可能会不同。

Creation time of String literals : 0 ms
Creation time of String objects with 'new' key word : 31 ms
Creation time of String objects with intern(): 16 ms

  

如何优化字符串连接? 

package com.xyc.springInstance;

/**
 * 
 * @ClassName:  StringConcatenate   
 * @Description:如何优化字符串连接?
 * @author: xyc 
 * @date:   2017年2月10日 上午11:18:52   
 *
 */
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("Time taken for string" + "concatenation using + operator : " + (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("Time taken for String concatenation" + "using StringBuffer : "+ (endTime1 - startTime1)+ " ms");
   }
}
View Code

上面的代码示例将产生以下结果:

Time taken for stringconcatenation using + operator : 0 ms
Time taken for String concatenationusing StringBuffer : 16 ms

  

如何判断字符串的Unicode码位?

package com.xyc.springInstance;
/**
 * 
 * @ClassName:  StringUniCode   
 * @Description:如何判断字符串的Unicode码位?
 * @author: xyc 
 * @date:   2017年2月10日 下午12:38:05   
 *
 */
public class StringUniCode{
    
   public static void main(String[] args){
       
      String test_string="Welcome to TutorialsPoint";
      System.out.println("String under test is = "+test_string);
      //返回指定索引的前一个字符的编码(Unicode 代码点)
      //如下返回第五个字符m的前一个字符o的编码
      System.out.println("Unicode code point at" +" position 5 in the string is = "+  test_string.codePointBefore(5));
      
   }
}
View Code

上面的代码示例将产生以下结果:

String under test is = Welcome to TutorialsPoint
Unicode code point at position 5 in the string is = 111

  

  

转载于:https://www.cnblogs.com/yuchao521/p/6382050.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值