JAVA基础

来源:互联网 发布:韩国制衣软件 编辑:程序博客网 时间:2024/04/30 20:08
/** * 字符串的复制 * 字符串的比较 - compareTo()   equalsIgnoreCase() * 查找字符串中是否包含某个字符 - indexOf() * 字符串的截取  - substring() * 字符串替换 - replace * 判断某字符串是否以指定字符串开始或结尾 - startsWith()  endsWith() * 转换字符串大小写 - toUpperCase()  toLowerCase() *  * @author LXL 2017年4月1日 */public class StringAndChar {public static void main(String[] args) {char[] a = { 'a', 's', 'd', 'f' };String str = new String(a);//String str2 = a; // 这句会报错. 因为类型不一样System.out.println("str = " + str); // str = asdfString str1 = "aaaa";String str2 = "aaaa";String str3 = "ASDF";/** * 字符串的比较 - compareTo() * 按字典顺序比较两个字符串. 基于字符串中各个字符的Unicode值 */System.out.println("str.compareTo(str1) --- " + str.compareTo(str1)); // 18/** * 字符串的相等 * equals() * equalsIgnoreCase() 不区分大小写 */// equals()System.out.println("str.equals(str1) --- " + str.equals(str1)); // falseSystem.out.println("str2.equals(str1) --- " + str2.equals(str1)); // true// equalsIgnoreCase() 不区分大小写System.out.println("str.equalsIgnoreCase(str3) --- " + str.equalsIgnoreCase(str3)); // true/** * indexOf() : 查找字符串中是否包含某个字符 */String email = "aaa@qq.com@";int index = email.indexOf("@");if (index != -1) {System.out.println(email + "  邮箱正确   " + "index --- " + index); // 邮箱正确   index --- 3} else {System.out.println(email + "  邮箱不正确   " + "index --- " + index); // 如果把两个@都去掉,打印为: 邮箱不正确 index --- -1}/** * 字符串的截取  - str.substring(i)  str.substring(beginIndex, endIndex) * str.substring(i) : 从index = i的位置开始显示 . i位置的字符也显示 * str.substring(beginIndex, endIndex) : 从begin的位置开始显示, 到end的位置结束, begin位置的字符显示, end位置的不显示 */String s_substring = "helloworld";System.out.println(s_substring + ".substring(3) = " + s_substring.substring(3)); // loworldSystem.out.println(s_substring + ".substring(2, 6) = " + s_substring.substring(2, 6)); // llow/** * 字符串替换 - replace(oldChar, newChar) : 使用后原字符串不发生改变 */String replace1 = "ABCDEFG";String replace2 = replace1.replace('C', 'Z');System.out.println(replace1 + "  " + replace2); // ABCDEFG  ABZDEFG/** * 判断某字符串是否以指定字符串开始或结尾 * startsWith()  endsWith() */String id = "130406000000000000";if (id.startsWith("130")) { // 以开头为河北省System.out.print("河北省, ");}for (int i = 0; i < 10; i++, i++) {if (id.endsWith(i + "")) { // 以尾号判断性别System.out.println("女");}} // 河北省, 女/** * 转换字符串大小写 - toUpperCase()  toLowerCase() * 使用后原字符串大小写不变 */String strSmall = "asdfg";String strSmall2 = "QWER";System.out.println(strSmall.toUpperCase()); // ASDFGSystem.out.println(strSmall); // asdfgSystem.out.println(strSmall2.toLowerCase()); // qwer}}



String s1 = "aaa";s1 = s1 + "sss";String s2 = s1;System.out.println(s1); // aaasssSystem.out.println(s2); // aaasss

另一篇字符串替换的文章 : http://blog.csdn.net/qq_28261207/article/details/68924423

1 0
原创粉丝点击