Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

OSGL Tool (Part 3): The Art of String Manipulation

DZone's Guide to

OSGL Tool (Part 3): The Art of String Manipulation

This post in this OSGL series focuses on string manipulation through code. Particularly, we'll see how to use code with the OSGL S utility to process String objects.

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

In the previous article, OSGL Tool: The Art of Image Processing, we introduced how to use the OSGL Img utility to process images in a fluent way:

source(img1())
        .resize(300, 400)
        .pipeline()
        .crop(50, 50, 250, 350)
        .pipeline()
        .watermark("HELLO OSGL")
        .writeTo("/tmp/img1_pipeline.png");


The way we designed our API greatly improved the readability of the code. We call this Fluent Coding. In this article, we will talk about how to use the OSGL S utility to manipulate String objects, including using Fluent APIs to improve readability and reduce ambiguity.

So let's show the code.

1. Predicates

1.1 Check If a String Is Null, Empty, or Blank

boolean b = S.isEmpty(""); // true
b = S.isEmpty(null); // true
b = S.isEmpty(" "); // false
b = S.isBlank(" "); // true
b = S.isNotEmpty("abc"); // true
b = S.isNotBlank("\t"); false
b = S.isAnyEmpty("", "xyz", ..); // true
b = S.isAllEmpty("", "xyz", ...); // false


1.2. Check If a String Is a Number

boolean b = S.isIntOrLong("12345"); // true
b = S.isIntOrLong("1234.5"); // false
b = S.isNumeric("1234.5"); // true


1.3 Use Fluent API to Predicate a String If There Are More Than One Parameters

boolean b = S.is("abc").contains("ab"); // true
b = S.is("abc").startsWith("ab"); // true
b = S.is("abc").endsWith("ab"); // false
b = S.is(null).equalsTo(null); // true
b = S.is(null).equalsTo(""); // true
b = S.is(null).equalsTo(" "); // false
b = S.is("[abc]").wrappedWith("[", "]"); // true
b = S.is("<abc>").wrappedWith(S.ANGLE_BRACKETS); // true


Note Keep in mind all that OSGL utility methods are null safe. That's why we do things like S.is(foo).contains(bar) instead of foo.contains(bar).

2. Equality

yes(S.eq("foo", "foo"));
yes(S.eq("foo", "Foo", S.IGNORECASE));
no(S.eq("foobar", " FooBar "));
yes(S.eq("foobar", " FooBar ", S.IGNORESPACE | S.IGNORECASE));
yes(S.eq(null, null));
no(S.eq(null, "foo"));


3. Format

String s = S.fmt("hello %s", "world"); // hello world
s = S.msgFmt("hello {0}", "world"); // hello world


4. Validation

String s = S.requireNotEmpty("foo"); // foo
s = S.requireNotBlank("bar"); // bar
s = S.requireNotEmpty(""); // raise IllegalArgumentException
s = S.requireNotBlank("  "); raise IllegalArgumentException


5. String Length

int n = S.len("abc"); // 3
n = S.len(null); // 0


6. Split

List<String> list = S.fastSplit("/tmp/foo/bar", "/"); [tmp, foo, bar]
S.List list = S.split("abc5xyz132ijk", ":"); [abc, xyz, ijk]
list = S.split("/tmp/foo/bar").by("/").get(); [tmp, foo, bar]
list = S.split("[abc]-[xyz]").by("-").stripElementWrapper(S.BRACKETS).get(); // [abc, xyz]


7. Concatenation

7.1 Concatenate Elements in a List Into a String

List<String> list = C.list("abc", "xyz");
String s = S.join(list).by("-").get(); // abc-xyz
s = S.join(list).by("-").wrapElementWith(S.SQUARE_BRACKETS).get(); // [abc]-[xyz]
list = S.list("abc", null, "xyz");
S.join(list).by("-").get(); // abc--xyz
S.join(list).by("-").ignoreEmptyElement().get(); // abc-xyz


7.2 Concatenate Multiple Objects

String s = S.concat("abc", 123); // abc123
s = S.concat("abc", null, 123); // abc123


7.3 Path Concatenation

eq("foo/bar", S.pathConcat("foo", '/', "bar"));
eq("foo/bar", S.pathConcat("foo/", '/', "bar"));
eq("foo/bar", S.pathConcat("foo", '/', "/bar"));
eq("foo/bar", S.pathConcat("foo/", '/', "/bar"));


9. Ensurance

eq("[abc]", S.ensure("abc").wrappedWith(S.SQUARE_BRACKETS));
eq("[abc]", S.ensure("[abc").wrappedWith(S.SQUARE_BRACKETS));
eq("[abc]", S.ensure("[abc]").wrappedWith(S.SQUARE_BRACKETS));
eq("abc", S.ensure("abc").strippedOff(S.ANGLE_BRACKETS));
eq("abc", S.ensure("<abc>").strippedOff(S.ANGLE_BRACKETS));
eq("_abc", S.ensure("abc").startWith('_'));
eq("abc.html", S.ensure("abc").endWith(".html"));


10. Replacement

String s;
s = S.given("hello world").replace("world").with("foo"); // hello foo
s = S.replace("world").in("hello world").with("foo"); // hello foo
s = S.replace("world").with("foo").in("hello world"); // hello foo
s = S.replace("[0-9]+").with("[N]").usingRegEx().in("times 10")); // times [N]


11. Repeat

eq("aaa", S.repeat('a').times(3));
eq("aaa", S.repeat('a').x(3));
eq("aaaaa", S.repeat('a').forFiveTimes());
eq("foofoo", S.repeat("foo").times(2));
eq("foofoo", S.repeat("foo").x(2));


12. Wrap

eq("*abc*", S.wrap("abc").with("*"));
eq("[abc]", S.wrap("abc").with("[", "]"));
eq("[abc]", S.wrap("abc").with(S.BRACKETS));
eq("(abc)", S.wrap("abc").with(S.PARENTHESES));
eq("<abc>", S.wrap("abc").with(S.DIAMOND));
eq("<abc>", S.wrap("abc").with(S.ANGLE_BRACKETS));
eq("《abc》", S.wrap("abc").with(S.书名号));


13. Strip

eq("abc", S.strip("[abc]").of(S.BRACKETS));
eq("abc", S.strip("<abc>").of(S.DIAMOND));
eq("abc", S.strip("*abc*").of("*"));
eq("abc", S.strip("111abc222").of("111", "222"));


14. Cut

eq("abc12", S.cut("abc123").by(5));
eq("ab", S.cut("abc123").first(2));
eq("23", S.cut("abc123").last(2));
eq("123", S.cut("abc123").after("abc"));
eq("abc", S.cut("abc123").before("123"));
eq("abc", S.cut("abc123abc123").before("123"));
eq("abc", S.cut("abc123abc123").beforeFirst("123"));
eq("abc123abc", S.cut("abc123abc123").beforeLast("123"));
eq("123", S.cut("abc123abc123").after("abc"));
eq("123", S.cut("abc123abc123").afterLast("abc"));
eq("123abc123", S.cut("abc123abc123").afterFirst("abc"));


15. Keyword transform

final String s = "Hello World";
eq("HelloWorld", S.camelCase(s));
eq("hello_world", S.underscore(s));
eq("hello-world", S.dashed(s));
eq("Hello World", S.capFirst(s));
eq("hello World", S.lowerFirst(s));
eq("Hello-World", Keyword.of(s).httpHeader());
eq("helloWorld", Keyword.of(s).javaVariable());
eq("HELLO_WORLD", Keyword.of(s).constantName());
eq("Hello world", Keyword.of(s).readable());


16. Counting

final String s = "1011101111";
eq(3, S.count("11").in(s));
eq(5, S.count("11").withOverlap().in(s));


17. Misc tools

eq("", S.trim(null));
eq("abc", S.trim(" abc"));
eq("abc\nxyz", S.dos2unix("abc\n\rxyz"));
eq("abc\n\rxyz", S.unix2dos("abc\nxyz"));
eq("this...", S.maxLength("this is a long text", 4));
yes(S.eq("foo", "foo"));
String s;
s = S.uuid(); // 9b2ec83d-15df-4746-9689-c82df5643832
s = S.random(); //kGYH$KCj
s = S.random(2); // gb
s = S.maxLength("this is a long text", 4); // this...


Summary

We have use code to illustrate how to use the OSGL S utility to process String objects. To get the OSGL library, add the following dependency into your pom.xml file:

<dependency>
    <groupId>org.osgl</groupId>
    <artifactId>osgl-tool</artifactId>
    <version>${osgl-tool.version}</version>
</dependency>


At the moment, the osgl-tool.version is 1.10.0.

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:
java ,string ,fluent api ,osgl ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}