Java方法-字符串

时间:2023-03-09 07:48:53
Java方法-字符串

【Java字符串】

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

//StringCompareEmp.java 文件

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()));
}
}

通过字符串函数 strOrig.lastIndexOf(Stringname) 来查找子字符串 Stringname 在 strOrig 出现的位置:

//SearchlastString.java 文件

public class SearchlastString {
public static void main(String[] args) {
String strOrig = "Hello world ,Hello Reader";
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);
}
}
}

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

//Main.java 文件

public class Main {
public static void main(String args[]) {
String str = "this is Java";
System.out.println(removeCharAt(str, 3));
}
public static String removeCharAt(String s, int pos) {
return s.substring(0, pos) + s.substring(pos + 1);
}
}

使用 java String 类的 replace 方法来替换字符串中的字符:

public class StringReplaceEmp{
public static void main(String args[]){
String str="Hello World";
System.out.println( str.replace( 'H','W' ) );
System.out.println( str.replaceFirst("He", "Wa") );
System.out.println( str.replaceAll("He", "Ha") );
}
}

使用 Java 的反转函数 reverse() 将字符串反转:

public class StringReverseExample{
public static void main(String[] args){
String string="abcdef";
String reverse = new StringBuffer(string).
reverse().toString();
System.out.println("\nString before reverse:
"+string);
System.out.println("String after reverse:
"+reverse);
}
}

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

//SearchStringEmp.java 文件

public class SearchStringEmp{
public static void main(String[] args) {
String strOrig = "Hello readers";
int intIndex = strOrig.indexOf("Hello");
if(intIndex == - 1){
System.out.println("Hello not found");
}else{
System.out.println("Found Hello at index "
+ intIndex);
}
}
}

split(string) 方法通过指定分隔符将字符串分割为数组:

//JavaStringSplitEmp.java 文件

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 = "jan.feb.march";
delimeter = "\\.";
temp = str.split(delimeter);
}
for(int i =0; i < temp.length ; i++){
System.out.println(temp[i]);
System.out.println("");
temp = str.split(delimeter,2);
for(int j =0; j < temp.length ; j++){
System.out.println(temp[i]);
}
}
}
}

使用 String toUpperCase() 方法将字符串从小写转为大写:

//StringToUpperCaseEmp.java 文件

public class StringToUpperCaseEmp {
public static void main(String[] args) {
String str = "string abc touppercase ";
String strUpper = str.toUpperCase();
System.out.println("Original String: " + str);
System.out.println("String changed to upper case: "
+ strUpper);
}
}

regionMatches() 方法测试两个字符串区域是否相等:

//StringRegionMatch.java 文件

public class StringRegionMatch{
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);
}
}

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

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

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

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

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

//StringComparePerformance.java 文件

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("通过 String 关键词创建字符串"
+ " : "+ (endTime - startTime)
+ " 毫秒" );
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("通过 String 对象创建字符串"
+ " : " + (endTime1 - startTime1)
+ " 毫秒");
}
}

结果:

通过 String 关键词创建字符串 :  毫秒
通过 String 对象创建字符串 : 毫秒

String.intern() 方法优化字符串:

//StringOptimization.java 文件

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");
variables[i] = variables[i].intern();
}
long endTime2 = System.currentTimeMillis();
System.out.println("Creation time of"
+ " String objects with intern(): "
+ (endTime2 - startTime2)
+ " ms");
}
}

format() 方法来格式化字符串,还可以指定地区来格式化():

//StringFormat.java 文件

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.GERMANY, "%-10.4f%n%n", e); //指定本地为德国(GERMANY)
}
}

结果:

2.718282
,

详解参考:http://blog.csdn.net/thc1987/article/details/17528093

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

//StringConcatenate.java 文件

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");
}
}

结果:

字符串连接 - 使用 + 操作符 :  ms
字符串连接 - 使用 StringBuffer : ms