1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//! String utility functions
//!
//! This module provides comprehensive string manipulation utilities,
//! inspired by Hutool's CharSequenceUtil.
use regex::Regex;
/// String utility functions
pub struct StrUtil;
impl StrUtil {
/// The null string constant: "null"
pub const NULL: &str = "null";
/// The empty string constant: ""
pub const EMPTY: &str = "";
/// The space string constant: " "
pub const SPACE: &str = " ";
/// Check if a string is empty (null or zero length)
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::is_empty(""), true);
/// assert_eq!(StrUtil::is_empty(" "), false); // contains spaces
/// assert_eq!(StrUtil::is_empty("abc"), false);
/// ```
pub fn is_empty(s: &str) -> bool {
s.is_empty()
}
/// Check if a string is empty or contains only whitespace characters
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::is_blank(""), true);
/// assert_eq!(StrUtil::is_blank(" "), true); // only whitespace
/// assert_eq!(StrUtil::is_blank(" \t\n "), true); // mixed whitespace
/// assert_eq!(StrUtil::is_blank("abc"), false);
/// ```
pub fn is_blank(s: &str) -> bool {
s.trim().is_empty()
}
/// Check if a string is not empty
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::is_not_empty("abc"), true);
/// assert_eq!(StrUtil::is_not_empty(""), false);
/// ```
pub fn is_not_empty(s: &str) -> bool {
!s.is_empty()
}
/// Check if a string is not blank (not empty and not only whitespace)
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::is_not_blank("abc"), true);
/// assert_eq!(StrUtil::is_not_blank(" "), false);
/// assert_eq!(StrUtil::is_not_blank(""), false);
/// ```
pub fn is_not_blank(s: &str) -> bool {
!Self::is_blank(s)
}
/// Trim whitespace from both ends of a string
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::trim(" hello "), "hello");
/// assert_eq!(StrUtil::trim(""), "");
/// ```
pub fn trim(s: &str) -> &str {
s.trim()
}
/// Trim whitespace from the start of a string
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::trim_start(" hello "), "hello ");
/// ```
pub fn trim_start(s: &str) -> &str {
s.trim_start()
}
/// Trim whitespace from the end of a string
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::trim_end(" hello "), " hello");
/// ```
pub fn trim_end(s: &str) -> &str {
s.trim_end()
}
/// Remove all whitespace characters from a string
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::remove_all_whitespace("a b c"), "abc");
/// assert_eq!(StrUtil::remove_all_whitespace("a\tb\nc"), "abc");
/// ```
pub fn remove_all_whitespace(s: &str) -> String {
s.chars()
.filter(|c| !c.is_whitespace())
.collect()
}
/// Convert string to lowercase
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::to_lower_case("HELLO"), "hello");
/// ```
pub fn to_lower_case(s: &str) -> String {
s.to_lowercase()
}
/// Convert string to uppercase
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::to_upper_case("hello"), "HELLO");
/// ```
pub fn to_upper_case(s: &str) -> String {
s.to_uppercase()
}
/// Capitalize the first character of a string
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::capitalize("hello"), "Hello");
/// assert_eq!(StrUtil::capitalize("HELLO"), "HELLO");
/// ```
pub fn capitalize(s: &str) -> String {
let mut chars = s.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
}
}
/// Convert string to camelCase
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::to_camel_case("hello_world"), "helloWorld");
/// assert_eq!(StrUtil::to_camel_case("user_name_test"), "userNameTest");
/// ```
pub fn to_camel_case(s: &str) -> String {
let parts: Vec<&str> = s.split('_').collect();
if parts.is_empty() {
return String::new();
}
let mut result = parts[0].to_lowercase();
for part in parts.iter().skip(1) {
result.push_str(&Self::capitalize(part));
}
result
}
/// Convert string to PascalCase
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::to_pascal_case("hello_world"), "HelloWorld");
/// assert_eq!(StrUtil::to_pascal_case("user_name"), "UserName");
/// ```
pub fn to_pascal_case(s: &str) -> String {
let parts: Vec<&str> = s.split('_').collect();
let mut result = String::new();
for part in parts {
result.push_str(&Self::capitalize(part));
}
result
}
/// Convert string to snake_case
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::to_snake_case("HelloWorld"), "hello_world");
/// assert_eq!(StrUtil::to_snake_case("UserName"), "user_name");
/// ```
pub fn to_snake_case(s: &str) -> String {
let mut result = String::new();
for (i, ch) in s.char_indices() {
if ch.is_uppercase() && i > 0 {
result.push('_');
}
result.push(ch.to_ascii_lowercase());
}
result
}
/// Check if string starts with the specified prefix
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::starts_with("hello world", "hello"), true);
/// assert_eq!(StrUtil::starts_with("hello world", "world"), false);
/// ```
pub fn starts_with(s: &str, prefix: &str) -> bool {
s.starts_with(prefix)
}
/// Check if string ends with the specified suffix
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::ends_with("hello world", "world"), true);
/// assert_eq!(StrUtil::ends_with("hello world", "hello"), false);
/// ```
pub fn ends_with(s: &str, suffix: &str) -> bool {
s.ends_with(suffix)
}
/// Check if string contains the specified substring
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::contains("hello world", "world"), true);
/// assert_eq!(StrUtil::contains("hello world", "test"), false);
/// ```
pub fn contains(s: &str, substr: &str) -> bool {
s.contains(substr)
}
/// Get substring from start index to end index
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::sub_string("hello world", 6, 11), "world");
/// ```
pub fn sub_string(s: &str, start: usize, end: usize) -> &str {
if start >= s.len() || start >= end {
return "";
}
let end = end.min(s.len());
&s[start..end]
}
/// Get substring from start index to end of string
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::sub_string_from("hello world", 6), "world");
/// ```
pub fn sub_string_from(s: &str, start: usize) -> &str {
if start >= s.len() {
return "";
}
&s[start..]
}
/// Replace all occurrences of a substring
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::replace("hello world", "world", "rust"), "hello rust");
/// ```
pub fn replace(s: &str, from: &str, to: &str) -> String {
s.replace(from, to)
}
/// Replace first occurrence of a substring
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::replace_first("hello world world", "world", "rust"), "hello rust world");
/// ```
pub fn replace_first(s: &str, from: &str, to: &str) -> String {
if let Some(pos) = s.find(from) {
let mut result = String::with_capacity(s.len() + to.len() - from.len());
result.push_str(&s[..pos]);
result.push_str(to);
result.push_str(&s[pos + from.len()..]);
result
} else {
s.to_string()
}
}
/// Replace last occurrence of a substring
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::replace_last("hello world world", "world", "rust"), "hello world rust");
/// ```
pub fn replace_last(s: &str, from: &str, to: &str) -> String {
if let Some(pos) = s.rfind(from) {
let mut result = String::with_capacity(s.len() + to.len() - from.len());
result.push_str(&s[..pos]);
result.push_str(to);
result.push_str(&s[pos + from.len()..]);
result
} else {
s.to_string()
}
}
/// Split string by delimiter
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// let result = StrUtil::split("a,b,c", ",");
/// assert_eq!(result, vec!["a", "b", "c"]);
/// ```
pub fn split(s: &str, delimiter: &str) -> Vec<String> {
s.split(delimiter)
.map(|s| s.to_string())
.collect()
}
/// Join strings with delimiter
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// let result = StrUtil::join(&["a", "b", "c"], ",");
/// assert_eq!(result, "a,b,c");
/// ```
pub fn join(strings: &[&str], delimiter: &str) -> String {
strings.join(delimiter)
}
/// Format string with arguments
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// let result = StrUtil::format("Hello, {0}!", &["World"]);
/// assert_eq!(result, "Hello, World!");
///
/// let result = StrUtil::format("{0} + {1} = {2}", &["1", "2", "3"]);
/// assert_eq!(result, "1 + 2 = 3");
/// ```
pub fn format(template: &str, args: &[&str]) -> String {
let mut result = template.to_string();
for (i, arg) in args.iter().enumerate() {
let placeholder = format!("{{{}}}", i);
result = result.replace(&placeholder, arg);
}
result
}
/// Check if string matches regex pattern
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::matches("hello123", r"^[a-z]+\d+$").unwrap(), true);
/// assert_eq!(StrUtil::matches("hello", r"^[a-z]+\d+$").unwrap(), false);
/// ```
pub fn matches(s: &str, pattern: &str) -> Result<bool, regex::Error> {
let regex = Regex::new(pattern)?;
Ok(regex.is_match(s))
}
/// Extract first match from regex pattern
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// let result = StrUtil::extract_first("hello123world", r"\d+").unwrap();
/// assert_eq!(result, Some("123".to_string()));
/// ```
pub fn extract_first(s: &str, pattern: &str) -> Result<Option<String>, regex::Error> {
let regex = Regex::new(pattern)?;
Ok(regex.find(s).map(|m| m.as_str().to_string()))
}
/// Extract all matches from regex pattern
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// let result = StrUtil::extract_all("a1b2c3", r"\d+").unwrap();
/// assert_eq!(result, vec!["1", "2", "3"]);
/// ```
pub fn extract_all(s: &str, pattern: &str) -> Result<Vec<String>, regex::Error> {
let regex = Regex::new(pattern)?;
Ok(regex.find_iter(s)
.map(|m| m.as_str().to_string())
.collect())
}
/// Reverse a string
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::reverse("hello"), "olleh");
/// assert_eq!(StrUtil::reverse("123"), "321");
/// ```
pub fn reverse(s: &str) -> String {
s.chars().rev().collect()
}
/// Pad string to the left with specified character to reach target length
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::pad_left("5", 3, '0'), "005");
/// assert_eq!(StrUtil::pad_left("hello", 3, ' '), "hello");
/// ```
pub fn pad_left(s: &str, length: usize, pad_char: char) -> String {
if s.len() >= length {
s.to_string()
} else {
let pad_len = length - s.len();
let padding = std::iter::repeat(pad_char).take(pad_len).collect::<String>();
padding + s
}
}
/// Pad string to the right with specified character to reach target length
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::pad_right("5", 3, '0'), "500");
/// assert_eq!(StrUtil::pad_right("hello", 3, ' '), "hello");
/// ```
pub fn pad_right(s: &str, length: usize, pad_char: char) -> String {
if s.len() >= length {
s.to_string()
} else {
let pad_len = length - s.len();
let padding = std::iter::repeat(pad_char).take(pad_len).collect::<String>();
s.to_string() + &padding
}
}
/// Center string with padding to reach target length
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::center("abc", 7, ' '), " abc ");
/// assert_eq!(StrUtil::center("hello", 3, ' '), "hello");
/// ```
pub fn center(s: &str, length: usize, pad_char: char) -> String {
if s.len() >= length {
s.to_string()
} else {
let total_pad = length - s.len();
let left_pad = total_pad / 2;
let right_pad = total_pad - left_pad;
let left_padding = std::iter::repeat(pad_char).take(left_pad).collect::<String>();
let right_padding = std::iter::repeat(pad_char).take(right_pad).collect::<String>();
left_padding + s + &right_padding
}
}
/// Check if all strings in the slice are blank
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::is_all_blank(&["", " ", "\t"]), true);
/// assert_eq!(StrUtil::is_all_blank(&["", "hello"]), false);
/// ```
pub fn is_all_blank(strings: &[&str]) -> bool {
strings.iter().all(|s| Self::is_blank(s))
}
/// Check if any string in the slice is blank
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::has_blank(&["hello", "", "world"]), true);
/// assert_eq!(StrUtil::has_blank(&["hello", "world"]), false);
/// ```
pub fn has_blank(strings: &[&str]) -> bool {
strings.iter().any(|s| Self::is_blank(s))
}
/// Check if all strings in the slice are not blank
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// assert_eq!(StrUtil::is_all_not_blank(&["hello", "world"]), true);
/// assert_eq!(StrUtil::is_all_not_blank(&["hello", ""]), false);
/// ```
pub fn is_all_not_blank(strings: &[&str]) -> bool {
strings.iter().all(|s| Self::is_not_blank(s))
}
/// Generate a random string of specified length
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// let random_str = StrUtil::random_string(10);
/// assert_eq!(random_str.len(), 10);
/// ```
pub fn random_string(length: usize) -> String {
use rand::{Rng, thread_rng};
const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let mut rng = thread_rng();
(0..length)
.map(|_| {
let idx = rng.gen_range(0..CHARSET.len());
CHARSET[idx] as char
})
.collect()
}
/// Generate a random alphanumeric string of specified length
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// let random_str = StrUtil::random_alphanumeric(8);
/// assert_eq!(random_str.len(), 8);
/// // Should only contain letters and numbers
/// assert!(random_str.chars().all(|c| c.is_alphanumeric()));
/// ```
pub fn random_alphanumeric(length: usize) -> String {
Self::random_string(length)
}
/// Generate a random numeric string of specified length
///
/// # Examples
///
/// ```rust
/// use yimi_rutool::core::StrUtil;
///
/// let random_num = StrUtil::random_numeric(5);
/// assert_eq!(random_num.len(), 5);
/// // Should only contain digits
/// assert!(random_num.chars().all(|c| c.is_numeric()));
/// ```
pub fn random_numeric(length: usize) -> String {
use rand::{Rng, thread_rng};
const DIGITS: &[u8] = b"0123456789";
let mut rng = thread_rng();
(0..length)
.map(|_| {
let idx = rng.gen_range(0..DIGITS.len());
DIGITS[idx] as char
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_empty() {
assert!(StrUtil::is_empty(""));
assert!(!StrUtil::is_empty("hello"));
}
#[test]
fn test_is_blank() {
assert!(StrUtil::is_blank(""));
assert!(StrUtil::is_blank(" "));
assert!(StrUtil::is_blank(" \t\n "));
assert!(!StrUtil::is_blank("hello"));
}
#[test]
fn test_trim() {
assert_eq!(StrUtil::trim(" hello "), "hello");
assert_eq!(StrUtil::trim(""), "");
assert_eq!(StrUtil::trim("no spaces"), "no spaces");
}
#[test]
fn test_to_camel_case() {
assert_eq!(StrUtil::to_camel_case("hello_world"), "helloWorld");
assert_eq!(StrUtil::to_camel_case("user_name_test"), "userNameTest");
assert_eq!(StrUtil::to_camel_case("single"), "single");
}
#[test]
fn test_to_snake_case() {
assert_eq!(StrUtil::to_snake_case("HelloWorld"), "hello_world");
assert_eq!(StrUtil::to_snake_case("UserName"), "user_name");
assert_eq!(StrUtil::to_snake_case("single"), "single");
}
#[test]
fn test_replace() {
assert_eq!(StrUtil::replace("hello world", "world", "rust"), "hello rust");
assert_eq!(StrUtil::replace("aaa", "a", "b"), "bbb");
}
#[test]
fn test_format() {
assert_eq!(StrUtil::format("Hello, {0}!", &["World"]), "Hello, World!");
assert_eq!(StrUtil::format("{0} + {1} = {2}", &["1", "2", "3"]), "1 + 2 = 3");
}
#[test]
fn test_pad_left() {
assert_eq!(StrUtil::pad_left("5", 3, '0'), "005");
assert_eq!(StrUtil::pad_left("hello", 3, ' '), "hello");
}
#[test]
fn test_pad_right() {
assert_eq!(StrUtil::pad_right("5", 3, '0'), "500");
assert_eq!(StrUtil::pad_right("hello", 3, ' '), "hello");
}
#[test]
fn test_center() {
assert_eq!(StrUtil::center("abc", 7, ' '), " abc ");
assert_eq!(StrUtil::center("hello", 3, ' '), "hello");
}
#[test]
fn test_random_string() {
let s1 = StrUtil::random_string(10);
let s2 = StrUtil::random_string(10);
assert_eq!(s1.len(), 10);
assert_eq!(s2.len(), 10);
assert_ne!(s1, s2); // Should be different (with very high probability)
}
#[test]
fn test_random_numeric() {
let s = StrUtil::random_numeric(5);
assert_eq!(s.len(), 5);
assert!(s.chars().all(|c| c.is_numeric()));
}
}