or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-utilities.mdbuilders.mdconcurrent-utilities.mddate-time-utilities.mdexception-utilities.mdindex.mdmath-utilities.mdobject-utilities.mdstring-utilities.mdvalidation-utilities.md

string-utilities.mddocs/

0

# String Utilities

1

2

Apache Commons Lang provides comprehensive string manipulation utilities through several key classes. The StringUtils class alone offers 233 static methods for null-safe string operations, making it one of the most essential utility classes for Java developers.

3

4

## Core Classes

5

6

### StringUtils - Comprehensive String Operations

7

8

The primary string utility class with 233 static methods covering every aspect of string manipulation:

9

10

```java { .api }

11

import org.apache.commons.lang3.StringUtils;

12

```

13

14

#### Null Safety and Basic Checks

15

16

```java { .api }

17

// Null safety

18

public static boolean isEmpty(CharSequence cs)

19

public static boolean isNotEmpty(CharSequence cs)

20

public static boolean isBlank(CharSequence cs)

21

public static boolean isNotBlank(CharSequence cs)

22

23

// Default value handling

24

public static String defaultString(String str)

25

public static String defaultString(String str, String defaultStr)

26

public static String defaultIfEmpty(String str, String defaultStr)

27

public static String defaultIfBlank(String str, String defaultStr)

28

```

29

30

**Usage Examples:**

31

```java { .api }

32

// Null and empty checks

33

boolean empty = StringUtils.isEmpty(null); // true

34

boolean empty2 = StringUtils.isEmpty(""); // true

35

boolean empty3 = StringUtils.isEmpty(" "); // false

36

37

boolean blank = StringUtils.isBlank(null); // true

38

boolean blank2 = StringUtils.isBlank(""); // true

39

boolean blank3 = StringUtils.isBlank(" "); // true

40

boolean blank4 = StringUtils.isBlank(" \t\n "); // true

41

42

// Default values

43

String result1 = StringUtils.defaultString(null); // ""

44

String result2 = StringUtils.defaultString(null, "default"); // "default"

45

String result3 = StringUtils.defaultIfEmpty("", "default"); // "default"

46

String result4 = StringUtils.defaultIfBlank(" ", "default"); // "default"

47

```

48

49

#### String Cleaning and Trimming

50

51

```java { .api }

52

// Trimming operations

53

public static String trim(String str)

54

public static String trimToNull(String str)

55

public static String trimToEmpty(String str)

56

public static String strip(String str)

57

public static String stripToNull(String str)

58

public static String stripToEmpty(String str)

59

60

// Advanced cleaning

61

public static String deleteWhitespace(String str)

62

public static String normalizeSpace(String str)

63

public static String clean(String str)

64

```

65

66

**Usage Examples:**

67

```java { .api }

68

// Basic trimming

69

String trimmed = StringUtils.trim(" hello "); // "hello"

70

String trimNull = StringUtils.trimToNull(" "); // null

71

String trimEmpty = StringUtils.trimToEmpty(" "); // ""

72

73

// Whitespace operations

74

String noWhitespace = StringUtils.deleteWhitespace("a b c"); // "abc"

75

String normalized = StringUtils.normalizeSpace("a b c"); // "a b c"

76

```

77

78

#### String Comparison and Matching

79

80

```java { .api }

81

// Case-sensitive comparison

82

public static boolean equals(CharSequence cs1, CharSequence cs2)

83

public static boolean equalsAny(CharSequence string, CharSequence... searchStrings)

84

public static int compare(String str1, String str2)

85

86

// Case-insensitive comparison

87

public static boolean equalsIgnoreCase(CharSequence str1, CharSequence str2)

88

public static boolean equalsAnyIgnoreCase(CharSequence string, CharSequence... searchStrings)

89

public static int compareIgnoreCase(String str1, String str2)

90

91

// Pattern matching

92

public static boolean startsWith(CharSequence str, CharSequence prefix)

93

public static boolean startsWithIgnoreCase(CharSequence str, CharSequence prefix)

94

public static boolean endsWith(CharSequence str, CharSequence suffix)

95

public static boolean endsWithIgnoreCase(CharSequence str, CharSequence suffix)

96

```

97

98

**Usage Examples:**

99

```java { .api }

100

// Null-safe comparison

101

boolean equal = StringUtils.equals(null, null); // true

102

boolean equal2 = StringUtils.equals("abc", "abc"); // true

103

boolean anyMatch = StringUtils.equalsAny("abc", "xyz", "abc"); // true

104

105

// Case-insensitive comparison

106

boolean equalIgnore = StringUtils.equalsIgnoreCase("ABC", "abc"); // true

107

boolean anyIgnore = StringUtils.equalsAnyIgnoreCase("ABC", "xyz", "abc"); // true

108

109

// Prefix/suffix checking

110

boolean starts = StringUtils.startsWith("filename.txt", "file"); // true

111

boolean ends = StringUtils.endsWith("filename.txt", ".txt"); // true

112

```

113

114

#### String Searching and Indexing

115

116

```java { .api }

117

// Basic searching

118

public static int indexOf(CharSequence seq, CharSequence searchSeq)

119

public static int lastIndexOf(CharSequence seq, CharSequence searchSeq)

120

public static boolean contains(CharSequence seq, CharSequence searchSeq)

121

public static boolean containsIgnoreCase(CharSequence str, CharSequence searchStr)

122

123

// Advanced searching

124

public static int indexOfAny(CharSequence cs, char... searchChars)

125

public static int indexOfAnyBut(CharSequence cs, char... searchChars)

126

public static boolean containsAny(CharSequence cs, char... searchChars)

127

public static boolean containsNone(CharSequence cs, char... searchChars)

128

public static boolean containsOnly(CharSequence cs, char... valid)

129

```

130

131

**Usage Examples:**

132

```java { .api }

133

// Basic search operations

134

int index = StringUtils.indexOf("hello world", "world"); // 6

135

boolean contains = StringUtils.contains("hello", "ell"); // true

136

boolean containsIgnore = StringUtils.containsIgnoreCase("Hello", "ELLO"); // true

137

138

// Character set operations

139

int anyIndex = StringUtils.indexOfAny("hello", 'a', 'e', 'i'); // 1

140

boolean hasVowels = StringUtils.containsAny("hello", "aeiou"); // true

141

boolean onlyLetters = StringUtils.containsOnly("hello", "abcdefghijklmnopqrstuvwxyz"); // true

142

```

143

144

#### String Manipulation and Formatting

145

146

```java { .api }

147

// Case conversion

148

public static String upperCase(String str)

149

public static String lowerCase(String str)

150

public static String capitalize(String str)

151

public static String uncapitalize(String str)

152

public static String swapCase(String str)

153

154

// Padding and centering

155

public static String leftPad(String str, int size)

156

public static String leftPad(String str, int size, char padChar)

157

public static String rightPad(String str, int size)

158

public static String rightPad(String str, int size, char padChar)

159

public static String center(String str, int size)

160

public static String center(String str, int size, char padChar)

161

```

162

163

**Usage Examples:**

164

```java { .api }

165

// Case operations

166

String upper = StringUtils.upperCase("hello"); // "HELLO"

167

String lower = StringUtils.lowerCase("HELLO"); // "hello"

168

String cap = StringUtils.capitalize("hello world"); // "Hello world"

169

String uncap = StringUtils.uncapitalize("Hello"); // "hello"

170

String swap = StringUtils.swapCase("Hello World"); // "hELLO wORLD"

171

172

// Padding operations

173

String leftPad = StringUtils.leftPad("123", 5, '0'); // "00123"

174

String rightPad = StringUtils.rightPad("123", 5, '0'); // "12300"

175

String centered = StringUtils.center("hello", 9, '-'); // "--hello--"

176

```

177

178

#### String Abbreviation and Truncation

179

180

```java { .api }

181

// Abbreviation

182

public static String abbreviate(String str, int maxWidth)

183

public static String abbreviate(String str, int offset, int maxWidth)

184

public static String abbreviate(String str, String abbrevMarker, int maxWidth)

185

public static String abbreviateMiddle(String str, String middle, int length)

186

187

// Truncation

188

public static String truncate(String str, int maxWidth)

189

public static String truncate(String str, int offset, int maxWidth)

190

```

191

192

**Usage Examples:**

193

```java { .api }

194

// Abbreviation with ellipsis

195

String abbrev1 = StringUtils.abbreviate("This is a long string", 10); // "This is..."

196

String abbrev2 = StringUtils.abbreviate("This is a long string", 5, 15); // "...long..."

197

String abbrev3 = StringUtils.abbreviateMiddle("This is a very long string", "...", 15); // "This...string"

198

199

// Simple truncation

200

String trunc = StringUtils.truncate("This is too long", 10); // "This is to"

201

```

202

203

#### String Joining and Splitting

204

205

```java { .api }

206

// Joining operations

207

public static String join(Object[] array)

208

public static String join(Object[] array, char separator)

209

public static String join(Object[] array, String separator)

210

public static String join(Iterable<?> iterable, String separator)

211

212

// Splitting operations

213

public static String[] split(String str)

214

public static String[] split(String str, char separatorChar)

215

public static String[] split(String str, String separatorChars)

216

public static String[] splitByWholeSeparator(String str, String separator)

217

```

218

219

**Usage Examples:**

220

```java { .api }

221

// Joining collections and arrays

222

String joined1 = StringUtils.join(new String[]{"a", "b", "c"}, ","); // "a,b,c"

223

String joined2 = StringUtils.join(Arrays.asList("x", "y", "z"), " | "); // "x | y | z"

224

225

// Splitting strings

226

String[] parts1 = StringUtils.split("a,b,c", ","); // ["a", "b", "c"]

227

String[] parts2 = StringUtils.split("one two three"); // ["one", "two", "three"]

228

String[] parts3 = StringUtils.splitByWholeSeparator("a::b::c", "::"); // ["a", "b", "c"]

229

```

230

231

### CharUtils - Character Operations

232

233

Provides 25 methods for character validation and manipulation:

234

235

```java { .api }

236

import org.apache.commons.lang3.CharUtils;

237

```

238

239

#### Character Classification

240

241

```java { .api }

242

// ASCII character validation

243

public static boolean isAscii(char ch)

244

public static boolean isAsciiPrintable(char ch)

245

public static boolean isAsciiControl(char ch)

246

247

// Character type checking

248

public static boolean isAsciiAlpha(char ch)

249

public static boolean isAsciiAlphaUpper(char ch)

250

public static boolean isAsciiAlphaLower(char ch)

251

public static boolean isAsciiNumeric(char ch)

252

public static boolean isAsciiAlphanumeric(char ch)

253

```

254

255

**Usage Examples:**

256

```java { .api }

257

// Character validation

258

boolean isAscii = CharUtils.isAscii('A'); // true

259

boolean isPrintable = CharUtils.isAsciiPrintable('\t'); // false

260

boolean isAlpha = CharUtils.isAsciiAlpha('Z'); // true

261

boolean isNumeric = CharUtils.isAsciiNumeric('5'); // true

262

boolean isAlphaNum = CharUtils.isAsciiAlphanumeric('A'); // true

263

```

264

265

#### Character Conversion

266

267

```java { .api }

268

// Character conversion

269

public static char toChar(Character ch)

270

public static char toChar(Character ch, char defaultValue)

271

public static char toChar(String str)

272

public static char toChar(String str, char defaultValue)

273

274

// Character constants

275

public static final char LF = '\n'

276

public static final char CR = '\r'

277

public static final char NUL = '\0'

278

```

279

280

**Usage Examples:**

281

```java { .api }

282

// Safe character conversion

283

char ch1 = CharUtils.toChar("A"); // 'A'

284

char ch2 = CharUtils.toChar(null, 'X'); // 'X'

285

char ch3 = CharUtils.toChar("", 'Y'); // 'Y'

286

287

// Using character constants

288

String lineEnding = "" + CharUtils.CR + CharUtils.LF; // "\r\n"

289

```

290

291

### CharSetUtils - Character Set Operations

292

293

Provides operations on character sets for advanced string manipulation:

294

295

```java { .api }

296

import org.apache.commons.lang3.CharSetUtils;

297

```

298

299

#### Character Set Operations

300

301

```java { .api }

302

// Character set testing and manipulation

303

public static boolean containsAny(String str, String... set)

304

public static int count(String str, String... set)

305

public static String delete(String str, String... set)

306

public static String keep(String str, String... set)

307

public static String squeeze(String str, String... set)

308

```

309

310

**Usage Examples:**

311

```java { .api }

312

// Character set operations

313

boolean hasVowels = CharSetUtils.containsAny("hello", "aeiou"); // true

314

int vowelCount = CharSetUtils.count("hello world", "aeiou"); // 3

315

String noVowels = CharSetUtils.delete("hello", "aeiou"); // "hll"

316

String onlyVowels = CharSetUtils.keep("hello", "aeiou"); // "eo"

317

String squeezed = CharSetUtils.squeeze("bookkeeper", "kep"); // "bokeper"

318

```

319

320

### RegExUtils - Regular Expression Utilities

321

322

Provides convenient methods for common regex operations:

323

324

```java { .api }

325

import org.apache.commons.lang3.RegExUtils;

326

```

327

328

#### Regex Operations

329

330

```java { .api }

331

// Pattern matching and replacement

332

public static String removeAll(String text, String regex)

333

public static String removeFirst(String text, String regex)

334

public static String replaceAll(String text, String regex, String replacement)

335

public static String replaceFirst(String text, String regex, String replacement)

336

public static String replacePattern(String source, String regex, String replacement)

337

```

338

339

**Usage Examples:**

340

```java { .api }

341

// Regex-based text processing

342

String noDigits = RegExUtils.removeAll("abc123def456", "\\d+"); // "abcdef"

343

String noFirstDigit = RegExUtils.removeFirst("abc123def456", "\\d+"); // "abcdef456"

344

String replaced = RegExUtils.replaceAll("foo123bar456", "\\d+", "X"); // "fooXbarX"

345

String firstOnly = RegExUtils.replaceFirst("foo123bar456", "\\d+", "X"); // "fooXbar456"

346

```

347

348

## Advanced String Processing

349

350

### String Escaping

351

352

For escaping strings for various formats:

353

354

```java { .api }

355

import org.apache.commons.lang3.StringEscapeUtils;

356

357

// Various escaping methods

358

public static String escapeHtml4(String input)

359

public static String unescapeHtml4(String input)

360

public static String escapeXml10(String input)

361

public static String unescapeXml(String input)

362

public static String escapeJava(String input)

363

public static String unescapeJava(String input)

364

public static String escapeJson(String input)

365

public static String unescapeJson(String input)

366

public static String escapeCsv(String input)

367

public static String unescapeCsv(String input)

368

```

369

370

**Usage Examples:**

371

```java { .api }

372

// HTML escaping

373

String htmlEscaped = StringEscapeUtils.escapeHtml4("Tom & Jerry"); // "Tom &amp; Jerry"

374

String htmlUnescaped = StringEscapeUtils.unescapeHtml4("Tom &amp; Jerry"); // "Tom & Jerry"

375

376

// JSON escaping

377

String jsonEscaped = StringEscapeUtils.escapeJson("He said \"Hello\""); // "He said \\\"Hello\\\""

378

String javaEscaped = StringEscapeUtils.escapeJava("Path: C:\\temp"); // "Path: C:\\\\temp"

379

```

380

381

## Performance Considerations

382

383

### Memory Efficiency

384

- StringUtils methods avoid unnecessary object creation

385

- Operations on null strings return appropriate defaults without exceptions

386

- String building operations use efficient internal buffers

387

388

### Thread Safety

389

All string utility methods are thread-safe and stateless, making them suitable for concurrent use.

390

391

### Common Patterns

392

393

```java { .api }

394

// Safe string processing pipeline

395

public String processUserInput(String input) {

396

return StringUtils.trimToEmpty(input) // Remove whitespace

397

.toLowerCase() // Normalize case

398

.replaceAll("[^a-z0-9]", "_") // Replace invalid chars

399

.replaceAll("_+", "_"); // Collapse multiple underscores

400

}

401

402

// Null-safe string comparison

403

public boolean areEqual(String str1, String str2) {

404

return StringUtils.equals(str1, str2); // Handles null values correctly

405

}

406

407

// Building user-friendly messages

408

public String formatMessage(String template, Object... args) {

409

if (StringUtils.isBlank(template)) {

410

return StringUtils.EMPTY;

411

}

412

return String.format(template, args);

413

}

414

```

415

416

## Integration with Other Libraries

417

418

### Spring Framework Integration

419

```java { .api }

420

@Component

421

public class StringProcessingService {

422

423

public String sanitizeInput(@NotNull String input) {

424

Validate.notNull(input, "Input cannot be null");

425

426

return StringUtils.trimToEmpty(input)

427

.toLowerCase()

428

.replaceAll("\\s+", " ");

429

}

430

431

public List<String> parseCommaSeparated(String input) {

432

if (StringUtils.isBlank(input)) {

433

return Collections.emptyList();

434

}

435

436

return Arrays.stream(StringUtils.split(input, ','))

437

.map(StringUtils::trim)

438

.filter(StringUtils::isNotBlank)

439

.collect(Collectors.toList());

440

}

441

}

442

```

443

444

### Validation Integration

445

```java { .api }

446

public class UserValidator {

447

448

public void validateUser(User user) {

449

Validate.notNull(user, "User cannot be null");

450

451

String name = StringUtils.trimToNull(user.getName());

452

Validate.notNull(name, "Name cannot be blank");

453

454

String email = StringUtils.trimToNull(user.getEmail());

455

Validate.notNull(email, "Email cannot be blank");

456

Validate.isTrue(StringUtils.contains(email, "@"), "Invalid email format");

457

}

458

}

459

```

460

461

The string utilities in Apache Commons Lang provide a comprehensive, null-safe, and performant foundation for all string processing needs in Java applications.