string: fix replace_each() (#9415)
							parent
							
								
									400b4027c9
								
							
						
					
					
						commit
						320cd00203
					
				|  | @ -329,15 +329,22 @@ pub fn (s string) replace_each(vals []string) string { | ||||||
| 	mut new_len := s.len | 	mut new_len := s.len | ||||||
| 	mut idxs := []RepIndex{} | 	mut idxs := []RepIndex{} | ||||||
| 	mut idx := 0 | 	mut idx := 0 | ||||||
|  | 	s_ := s.clone() | ||||||
| 	for rep_i := 0; rep_i < vals.len; rep_i += 2 { | 	for rep_i := 0; rep_i < vals.len; rep_i += 2 { | ||||||
| 		// vals: ['rep1, 'with1', 'rep2', 'with2']
 | 		// vals: ['rep1, 'with1', 'rep2', 'with2']
 | ||||||
| 		rep := vals[rep_i] | 		rep := vals[rep_i] | ||||||
| 		with := vals[rep_i + 1] | 		with := vals[rep_i + 1] | ||||||
| 		for { | 		for { | ||||||
| 			idx = s.index_after(rep, idx) | 			idx = s_.index_after(rep, idx) | ||||||
| 			if idx == -1 { | 			if idx == -1 { | ||||||
| 				break | 				break | ||||||
| 			} | 			} | ||||||
|  | 			// The string already found is set to `/del`, to avoid duplicate searches.
 | ||||||
|  | 			for i in 0 .. rep.len { | ||||||
|  | 				unsafe { | ||||||
|  | 					s_.str[idx + i] = 127 | ||||||
|  | 				} | ||||||
|  | 			} | ||||||
| 			// We need to remember both the position in the string,
 | 			// We need to remember both the position in the string,
 | ||||||
| 			// and which rep/with pair it refers to.
 | 			// and which rep/with pair it refers to.
 | ||||||
| 			idxs << RepIndex{ | 			idxs << RepIndex{ | ||||||
|  |  | ||||||
|  | @ -329,6 +329,8 @@ fn test_replace_each() { | ||||||
| 		'b', | 		'b', | ||||||
| 	]) | 	]) | ||||||
| 	assert y == 'bbbb' | 	assert y == 'bbbb' | ||||||
|  | 	s2 := 'hello_world hello' | ||||||
|  | 	assert s2.replace_each(['hello_world', 'aaa', 'hello', 'bbb']) == 'aaa bbb' | ||||||
| } | } | ||||||
| 
 | 
 | ||||||
| fn test_itoa() { | fn test_itoa() { | ||||||
|  |  | ||||||
		Loading…
	
		Reference in New Issue