JAVA-String类常用方法

来源:互联网 发布:淘宝ok球鞋店如何 编辑:程序博客网 时间:2024/05/16 10:19

菜鸟教程参考  http://www.runoob.com/java/java-string.html

一。字符串生成

public class csdnTest8{public static void main(String args[]){char[] helloArray = {'h','e','l','l','o','.'};   //字符数组String helloString = new String(helloArray);System.out.println( helloString);}}

二。连接字符串

public class csdnTest9{public static void main(String args[]){String str1="Fang ";String str2="Learning";System.out.println(str1.concat(str2));System.out.println(str1+"Learing"); //两种不同方式合并字符串}}

三。创建格式化字符串   String。format()的使用

转  换  符

说    明 

示    例

%s

字符串类型

"mingrisoft"

%c

字符类型

'm'

%b

布尔类型

true

%d

整数类型(十进制)

99

%x

整数类型(十六进制)

FF

%o

整数类型(八进制)

77

%f

浮点类型

99.99

%a

十六进制浮点类型

FF.35AE

%e

指数类型

9.38e+5

%g

通用浮点类型(f和e类型中较短的)

 

%h

散列码

 

%%

百分比类型

%n

换行符

 

%tx

日期与时间类型(x代表不同的日期与时间转换符

输出格式化数字可以使用printf()和format()方法

具体参考 http://blog.csdn.net/lonely_fireworks/article/details/7962171/


四。String方法使用

(1)Java compareTo()方法

public class csdnTest10{public static void main(String args[]){String str1="Strings";String str2="Strings";String str3="Learning";int result = str1.compareTo(str2);System.out.println(result);result = str2.compareTo( str3 );System.out.println(result); result = str3.compareTo( str1 );System.out.println(result);}}

(2) Java equals()方法

public class csdnTest10{public static void main(String args[]){String str1=new string("Strings");String Str2 = Str1;String Str3 =new String("Strings")boolean retvalretval = Str1.equals(Str2);System.out.println("返回值"+ retval);  //tretval = Str1.equals(Str3);System.out.println("返回值"+ retval);  //t}}

(3)Java matches()方法  检测字符串是否匹配给定的正则表达式。

public class csdnTest12 {public static void main(String args[]) {String Str = new String("www.runoob.com");System.out.print("返回值 :" );System.out.println(Str.matches("(.*)runoob(.*)"));System.out.print("返回值 :" );System.out.println(Str.matches("(.*)google(.*)"));System.out.print("返回值 :" );System.out.println(Str.matches("www(.*)"));}}

解决错误提示:编码 GBK 的不可映射字符,

使用命令:javac -encoding utf-8 helloword.java,编译成功


(4)Java StartWith()方法     startsWith() 方法用于检测字符串是否以指定的前缀开始。

<span style="font-size:14px;">public class Test {public static void main(String args[]) {        String Str = new String("www.runoob.com");        System.out.print("返回值 :" );        System.out.println(Str.startsWith("www") );        System.out.print("返回值 :" );        System.out.println(Str.startsWith("runoob") );        System.out.print("返回值 :" );        System.out.println(Str.startsWith("runoob", 4) );}}</span>







0 0
原创粉丝点击