Java Tutorial/Data Type/Extracting String Characters

Материал из Java эксперт
Версия от 15:26, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Beyond the last character of the substring

public class MainClass{
  public static void main(String[] arg){
    String place = "abcedfghijk";
    String segment = place.substring(7, 11);
    System.out.println(segment);
  }
}



hijk


Finding the last occurrence of "a" in the String variable text: the method lastIndexOf()

public class MainClass{
  public static void main(String[] arg){
    String str = "abcdea";
    
    int index = 0;        
    index = str.lastIndexOf("a");         
    System.out.println(index);
  }
}



5


Last index of

public class MainClass{
  public static void main(String[] arg){
    String str = "abcdeabcdef";
   
    int index = 0;        
    index = str.lastIndexOf("ab");         
    System.out.println(index);
  }
}



5


Searching for Substrings

public class MainClass{
  public static void main(String[] arg){
    String str = "abcdeabcdef";
    int startIndex = 3;
    
    int index = 0;        
    index = str.indexOf("ab", startIndex);         
    System.out.println(index);
  }
}



5


Searching Strings for Characters

public class MainClass{
  public static void main(String[] arg){
    String str = "abcde";
    
    int index = 0;        
    index = str.indexOf("c");  
    System.out.println(index);
  }
}



2


String Characters

public class StringCharacters {
  public static void main(String[] args) {
    String text = "To be or not to be?";
    int spaces = 0,
    vowels = 0, 
    letters = 0;
    for (int i = 0; i < text.length(); i++) {
      char ch = Character.toLowerCase(text.charAt(i));
      if (ch == "a" || ch == "e" || ch == "i" || ch == "o" || ch == "u")
        ++vowels;
      if (Character.isLetter(ch))
        ++letters;
      if (Character.isWhitespace(ch))
        ++spaces;
    }
  }
}





To search forwards from a given position: startIndex

public class MainClass{
  public static void main(String[] arg){
    String str = "abcdea";
    int startIndex = 3;
    
    int index = 0;        
    index = str.indexOf("a", startIndex);         
    System.out.println(index);
  }
}



5


Up to the end of the string

public class MainClass{
  public static void main(String[] arg){
    String place = "abcedfghijk";
    String lastWord = place.substring(5);
    System.out.println(lastWord);
  }
}



fghijk