@@ -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,
@@ -2465,6 +2506,18 @@ mod tests {
2465
2506
assert ~[ ] == words ( ~"") ;
2466
2507
}
2467
2508
2509
+ #[ test]
2510
+ fn test_split_within ( ) {
2511
+ assert split_within ( ~"", 0 ) == ~[ ] ;
2512
+ assert split_within ( ~"", 15 ) == ~[ ] ;
2513
+ assert split_within ( ~"hello", 15 ) == ~[ ~"hello"] ;
2514
+
2515
+ let data = ~"\n Mary had a little lamb\n Little lamb\n ";
2516
+ assert split_within ( data, 15 ) == ~[ ~"Mary had a little",
2517
+ ~"lamb Little ",
2518
+ ~"lamb"] ;
2519
+ }
2520
+
2468
2521
#[ test]
2469
2522
fn test_find_str ( ) {
2470
2523
// byte positions
@@ -2540,6 +2593,15 @@ mod tests {
2540
2593
t ( ~[ ~"hi"] , ~" ", ~" hi") ;
2541
2594
}
2542
2595
2596
+ #[ test]
2597
+ fn test_repeat ( ) {
2598
+ assert repeat ( ~"x", 4 ) == ~"xxxx";
2599
+ assert repeat ( ~"hi", 4 ) == ~"hihihihi";
2600
+ assert repeat ( ~"ไท华", 3 ) == ~"ไท华ไท华ไท华";
2601
+ assert repeat ( ~"", 4 ) == ~"";
2602
+ assert repeat ( ~"hi", 0 ) == ~"";
2603
+ }
2604
+
2543
2605
#[ test]
2544
2606
fn test_to_upper ( ) {
2545
2607
// libc::toupper, and hence str::to_upper
0 commit comments