Програмування на мові Java Робота з рядками
March 4th, 2009
« Програмування на мові Java Мережеві засоби | Програмування на мові Java Типи »
static String arr[] = {”Now”, “is”, “the”, “time”, “for”, “all”
“good”, “men”, “to”, “come”, “to”, “the”
“aid”, “of”, “their”, “country” };
public static void main(String args[]){
for (int j = 0; i < arr.length; j++) {
for (int i = j + 1; i < arr.length; i++) {
if (arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j]= arr[i];
arr[i]= t;
}
}
System.out.println(arr[j]);
}
} }
indexOf і lastIndexOf
В клас String включена підтримка пошуку певного символу або підрядка, для цього в нім є два метода-indexOf і lastIndexOf. Кожний з цих методів повертає індекс того символу, який ви хотіли знайти, або індекс початку шуканого підрядка. У будь-якому випадку, якщо пошук виявився невдалим методи повертають значення -1.
У черговому прикладі показано, як користуватися різними варіантами цих методів пошуку.
class indexOfDemo {
public static void main(String args[]){
String s = “Now is the time for all good men ” +
“to come to the aid of their country ” +
“and pay their due taxes.”;
System.out.println(s);
System.out.println(”indexOf(t)= ” + s.indexOf(’f'));
System.out.println(”lastlndexOf(t)= ” + s.lastlndexOf(’f'));
System.out.println(”indexOf(the)= ” + s.indexOf(”the”));
System.out.println(”lastlndexOf(the)= ” + s.lastlndexOf(”the”));
System.out.println(”indexOf(t, 10)= ” + s.indexOf(’f', 10));
System.out.println(”lastlndexOf(t, 50)= ” + s.lastlndexOf(’f', 50));
System.out.println(”indexOf(the, 10)= ” + s.indexOf(”the”, 10));
System.out.println(”lastlndexOf(the, 50)= ” + s.lastlndexOf(”the”, 50));
} }
Нижче приведений результат роботи цієї програми. Звернете увагу на те, що індекси в рядках починаються з нуля.
С:> java indexOfDemo
Now is the time for all good men to come to the aid of their country
and pay their due taxes.
indexOf(t)= 7
lastlndexOf(t)= 87
Pages: 1 2 3 4 5 6 7 8 9 10 11 12
Tags: клас, метод, обєкт, параметр, приклад, рядок, символ
програмування
Схожі записи
Категория: програмування |










