获取字符串的长度:使用length()
String s = "We are students";
System.out.println("字符串的长度:" +s.length );
获取指定字符的索引位置
String 类提供了indexOf()和lastindexOF()方法来获取指定字符的索引位置,不同的是,indexOf()方法返回的是搜索的字符首次出现位置的索引,而lastIndexOf()方法返回的是搜索的字符最后出现位置的索引。
public class Select {
public static void main(String[] args){
String s ="we are students";
System.out.println("字符s在字符串s中的位置是: " + s.indexOf("s"));//输出为7,说明从0开始。
}
}
//没有,就返回-1
获取指定索引位置的字符
使用String类的charAt()方法可获取指定索引处的字符,返回字符的索引;
public class CharAt {
public static void main(String[] args){
String s = "hello word";
char mychar2 = s.charAt(6);
System.out.println("字符串s中索引位置是6的字符为: " + mychar2);
}
}
Keine Kommentare:
Kommentar veröffentlichen