java---字符串操作(分割,大小写转化,去除首末空格,截取字串,转化成字符数组)

来源:互联网 发布:苹果电脑的制图软件 编辑:程序博客网 时间:2024/05/22 14:06

5、字符串分割: split()  

public class StringSplit {public static void main(String[] args) {String message = "So say we all!";// 定义字符串// split根据给定正则表达式的匹配拆分此字符串String[] split = message.split(" ");// 使用空格分割字符串System.out.println(message + "中共有" + split.length + "个单词!");System.out.println();String str = "boo:and:foo";System.out.println("原字符串为:" + str);String[] str1 = str.split(":");System.out.println("新字符串为:");for (int i = 0; i < str1.length; i++) {System.out.println(str1[i]);}System.out.println();System.out.println("原字符串为:" + str);String[] str2 = str.split("o");System.out.println("新字符串为:");for (int i = 0; i < str2.length; i++) {System.out.println(str2[i]);}System.out.println();}}

运行结果为:

So say we all!中共有4个单词!


原字符串为:boo:and:foo
新字符串为:
boo
and
foo


原字符串为:boo:and:foo
新字符串为:
b


:and:f


6、大小写转换: toUpperCase()、toLowerCase()  

public class StringCase {public static void main(String[] args) {String message = "So say we all!";// 定义字符串// toUpperCase使用默认语言环境的规则将字符串中的所有字符都转化为大写// public String toUpperCase()此方法等效于toUpperCase(Locale.getDefault());System.out.println(message);System.out.println("转换为大写形式:" + message.toUpperCase());// toLowerCase使用默认语言环境的规则将字符串中的所有字符都转化为小写// public String toUpperCase()此方法等效于toLowerCase(Locale.getDefault());System.out.println(message);System.out.println("转换为小写形式:" + message.toLowerCase());}}

运行结果为:

So say we all!
转换为大写形式:SO SAY WE ALL!
So say we all!
转换为小写形式:so say we all!


7、去除首末空格: trim()  

public class StringTrim {public static void main(String[] args) {String message = " So say we all! ";// 定义字符串System.out.println("字符串长度:" + message.length());// trim返回字符串的副本,忽略前导空格和尾部空格System.out.println("去除首末空格后字符串长度:" + message.trim().length());System.out.println();String str = "          ";System.out.println("字符串长度:" + str.length());// trim返回字符串的副本,忽略前导空格和尾部空格System.out.println("去除首末空格后字符串长度:" + str.trim().length());}}

运行结果为:

字符串长度:16
去除首末空格后字符串长度:14


字符串长度:10
去除首末空格后字符串长度:0


8、截取字串:
    String  substring(int beginIndex)      返回一个新的字符串,它是此字符串的一个子字符串。 
    String  substring(int beginIndex, int endIndex)  返回一个新字符串,它是此字符串的一个子字符串。

public class Test {public static void main(String[] args) {String str="adsnsdfh";//substring(beginIndex)获得一个以beginIndex为开始字符的字符串,直到此字符串末尾System.out.println(str.substring(4));//substring(beginIndex,endIndex)获得一个以beginIndex为开始字符、//以endIndex-1为结尾字符的字符串,注意endIndex不包括在内System.out.println(str.substring(2,7));}}

运行结果为:

sdfh
snsdf


9、转换成字符数组:   

        toCharArray()    将此字符串转换为一个新的字符数组。

public class Test {public static void main(String[] args) {String str="ad  snsddwev  fh";//toCharArray将此字符串转化为一个新的字符数组                 char[] message=str.toCharArray();System.out.println(message);}}

运行结果为:

ad  snsddwev  fh