String对象的声明和String对象的常用方法

来源:互联网 发布:人工智能最好的大学 编辑:程序博客网 时间:2024/05/17 02:48

String对象的声明和String对象的常用方法:

package string.test;import java.util.Scanner;/* * 定义一个String对象 * 了解String 方法 */public class StringStudy {public static void main(String[] args){String str = "asjfksdjk4lgdgkljslfgklgj";/*length()方法,返回字符串的长度 *int length = str.length(); */System.out.println("str字符串为:" + str);System.out.println("字符串str的长度是:" + str.length());//length()方法/* * charAt(int index)方法,返回索引处的char值 * 从0开始 */System.out.println("str字符串为:" + str);Scanner in = new Scanner(System.in);//charAt(int index)方法System.out.print("请输入要检索的位置:");int k = in.nextInt();System.out.println("检索到的字符为:" + str.charAt(k));/* * concat(String s)方法,将指定字符串连接到此字符串尾部 * 在本例中将字符串str1连接到字符串str的尾部 */String str1 = "abcd123";System.out.println("字符串str为:" + str);System.out.println("字符串str1为:" + str1);System.out.println("str余str1连接后的字符串为" + str.concat(str1));//concat(string s) 方法/* * contains(charSequence s)方法,用来判断此字符串是否包含指定字符串 * 其返回值为boolean类型(true/false) */String str2 = "asjf";  System.out.println("contains方法的返回值为:"+str.contains(str2));/* * equals(Object anObject)方法,用来将此字符串与指定的字符串比较 * 其返回值为boolean类型(true/false) */String str3 = "asdgesfd";System.out.println("equals方法的返回值为:" + str.equals(str3));/* * compareTo(String anotherString)方法,用来按字典顺序比较两个字符串 * 其返回值为: * 如果这个字符串是等参数字符串那么返回值0, * 如果这个字符串是按字典顺序小于字符串参数那么返回小于0的值, * 如果此字符串是按字典顺序大于字符串参数那么一个大于0的值 */String str4 = "asfdghhj";System.out.println("compareTo方法的返回值为:" + str.compareTo(str4));/* * indexOf(int ch)返回指定字符在此字符串中的第一次出现处的索引 *  */int t='4';System.out.println("indexOf方法的返回值:" + str.indexOf(t));/* * substring(int beginIndex)用来截取字符串,其截取的是从beginIndex到结尾的 * substring(int beginIndex,int endIndex)用来截取字符串,其截取的是从beginIndex到endIndex的 */String str5= "fghj536jfghj" ;System.out.println("字符串str5为:" + str5);System.out.println("从字符串str5的第四位截取的得到的字符串为:" + str5.substring(4));System.out.println("截取字符串的第6到第9位得到的字符串为:" + str5.substring(6,9));/* * toLower/upperCase()将指定字符串转化为小/大写字符串 */String str6= "ashdjw45" ;System.out.println("将字符串str6中的字母全部改为大写:" + str6.toUpperCase());/* * split(String regex)--根据匹配给定的字符串来拆分此字符串 */}}


1 0