@@ -203,6 +203,13 @@ pub pure fn connect(v: &[~str], sep: &str) -> ~str {
203
203
move s
204
204
}
205
205
206
+ /// Given a string, make a new string with repeated copies of it
207
+ pub fn repeat( ss : & str , nn : uint ) -> ~str {
208
+ let mut acc = ~"";
209
+ for nn. times { acc += ss; }
210
+ return acc;
211
+ }
212
+
206
213
/*
207
214
Section: Adding to and removing from a string
208
215
*/
@@ -573,6 +580,40 @@ pub pure fn words(s: &str) -> ~[~str] {
573
580
split_nonempty ( s, |c| char:: is_whitespace ( c) )
574
581
}
575
582
583
+ /** Split a string into a vector of substrings,
584
+ * each of which is less than a limit
585
+ */
586
+ pub fn split_within( ss : & str , lim : uint ) -> ~[ ~str ] {
587
+ let words = str:: words ( ss) ;
588
+
589
+ // empty?
590
+ if words == ~[ ] { return ~[ ] ; }
591
+
592
+ let mut rows : ~[ ~str ] = ~[ ] ;
593
+ let mut row : ~str = ~"";
594
+
595
+ for words. each |wptr| {
596
+ let word = * wptr;
597
+
598
+ // if adding this word to the row would go over the limit,
599
+ // then start a new row
600
+ if str:: len ( row) + str:: len ( word) + 1 > lim {
601
+ rows += [ row] ; // save previous row
602
+ row = word; // start a new one
603
+ } else {
604
+ if str:: len ( row) > 0 { row += ~" " } // separate words
605
+ row += word; // append to this row
606
+ }
607
+ }
608
+
609
+ // save the last row
610
+ if row != ~" " { rows += [ row] ; }
611
+
612
+ return rows;
613
+ }
614
+
615
+
616
+
576
617
/// Convert a string to lowercase. ASCII only
577
618
pub pure fn to_lower ( s : & str ) -> ~str {
578
619
map ( s,
@@ -2479,6 +2520,18 @@ mod tests {
2479
2520
assert ~[ ] == words ( ~"") ;
2480
2521
}
2481
2522
2523
+ #[ test]
2524
+ fn test_split_within ( ) {
2525
+ assert split_within ( ~"", 0 ) == ~[ ] ;
2526
+ assert split_within ( ~"", 15 ) == ~[ ] ;
2527
+ assert split_within ( ~"hello", 15 ) == ~[ ~"hello"] ;
2528
+
2529
+ let data = ~"\n Mary had a little lamb\n Little lamb\n ";
2530
+ assert split_within ( data, 15 ) == ~[ ~"Mary had a little",
2531
+ ~"lamb Little ",
2532
+ ~"lamb"] ;
2533
+ }
2534
+
2482
2535
#[ test]
2483
2536
fn test_find_str ( ) {
2484
2537
// byte positions
@@ -2554,6 +2607,15 @@ mod tests {
2554
2607
t ( ~[ ~"hi"] , ~" ", ~" hi") ;
2555
2608
}
2556
2609
2610
+ #[ test]
2611
+ fn test_repeat ( ) {
2612
+ assert repeat ( ~"x", 4 ) == ~"xxxx";
2613
+ assert repeat ( ~"hi", 4 ) == ~"hihihihi";
2614
+ assert repeat ( ~"ไท华", 3 ) == ~"ไท华ไท华ไท华";
2615
+ assert repeat ( ~"", 4 ) == ~"";
2616
+ assert repeat ( ~"hi", 0 ) == ~"";
2617
+ }
2618
+
2557
2619
#[ test]
2558
2620
fn test_to_upper ( ) {
2559
2621
// libc::toupper, and hence str::to_upper
0 commit comments