Bidi Splits Mixed Direction Text
Break a paragraph into directional runs with java.text.Bidi so renders can lay out LTR and RTL segments with correct bounds.
Code
import java.text.Bidi;
public class DirectionalRuns {
public static void main(String[] args) {
String mixed = "invoice #42 فاتورة total";
char[] chars = mixed.toCharArray();
// 快速预检:纯 LTR 文本根本不用构造 Bidi 对象
System.out.println("requires bidi analysis: "
+ Bidi.requiresBidi(chars, 0, chars.length));
Bidi bidi = new Bidi(mixed, Bidi.DIRECTION_LEFT_TO_RIGHT);
System.out.println("base direction LTR: " + bidi.baseIsLeftToRight());
System.out.println("run count: " + bidi.getRunCount());
for (int run = 0; run < bidi.getRunCount(); run++) {
int start = bidi.getRunStart(run);
int limit = bidi.getRunLimit(run);
// 奇数 level 是 RTL,偶数是 LTR
System.out.printf("run %d: [%d,%d) level=%d text=%s%n",
run, start, limit, bidi.getRunLevel(run),
mixed.substring(start, limit));
}
}
}How it works
The code’s whole job belongs to the class DirectionalRuns and the function main.
Repetition is confined to for (int run = 0; run < bidi.getRunCount(); run++) — the rest of the file is straight-line.
Watch out for
- Every symbol it touches is a language built-in — nothing to fetch.
Using it
Signature: public static void main(String[] args)
The demo output is labeled (requires bidi analysis:, base direction LTR:, run count:), so every printed line maps back to its originating operation.
Key statements
Bidi bidi = new Bidi(mixed, Bidi.DIRECTION_LEFT_TO_RIGHT);
String mixed = "invoice #42 فاتورة total";
char[] chars = mixed.toCharArray();
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.
FAQ
- What does Bidi Splits Mixed Direction Text print when run?
- The script runs standalone; its 4 labeled outputs include `requires bidi analysis:`, `base direction LTR:`, `run count:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.