BreakIterator preceding() method in Java with Examples
The preceding() method of java.text.BreakIterator class is used to get the index of the character of the last boundary preceding the boundary of specified character offset. It provides the offset of the first character of boundary which follows or precedes the current boundary pointed by BreakIterator.
Syntax:
public int preceding(int offset)
Parameter: it takes offset of the character for which the previous boundary has to be found.
Return Value: This method provides the index of boundary which precedes the specified character offset.
Exception: This method throws IllegalArgumentException if the specified index is less than the first text boundary or greater than the last text boundary.
Below are the examples to illustrate the preceding() method:
Example 1:
import java.text.*;
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] argv)
{
int current = 0 , next = 0 ;
BreakIterator wb
= BreakIterator.getWordInstance();
wb.setText( "Code Geeks" );
wb.next( 3 );
current = wb.current();
System.out.println(
"current position before"
+ " calling preceding() : "
+ current);
next = wb.preceding( 6 );
System.out.println(
"\ncurrent position after"
+ " calling 1st preceding() : "
+ next);
next = wb.preceding( 11 );
System.out.println(
"\ncurrent position after"
+ " calling 2nd preceding() : "
+ next);
}
}
|
Output:
current position before calling preceding() : 11
current position after calling 1st preceding() : 4
current position after calling 2nd preceding() : 6
Example 2:
import java.text.*;
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] argv)
{
try {
int current = 0 , next = 0 ;
BreakIterator wb
= BreakIterator.getWordInstance();
wb.setText( "Code Geeks" );
wb.next( 3 );
current = wb.current();
System.out.println(
"current position before"
+ " calling preceding() : "
+ current);
next = wb.preceding( 6 );
System.out.println(
"\ncurrent position after"
+ " calling 1st preceding() : "
+ next);
next = wb.preceding(- 1 );
System.out.println(
"\ncurrent position after"
+ " calling 2nd preceding() : "
+ next);
}
catch (IllegalArgumentException e) {
System.out.println(
"\noffset is less than the first boundary" );
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
current position before calling preceding() : 11
current position after calling 1st preceding() : 4
offset is less than the first boundary
Exception thrown : java.lang.IllegalArgumentException: offset out of bounds
Reference: https://docs.oracle.com/javase/9/docs/api/java/text/BreakIterator.html#preceding-int-
Last Updated :
27 Nov, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...