Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(632)

Side by Side Diff: sdk/lib/core/string.dart

Issue 23480035: Added examples to String docs. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Numerous post LGTM fixes. Created 7 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a 2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file. 3 // BSD-style license that can be found in the LICENSE file.
4 4
5 part of dart.core; 5 part of dart.core;
6 6
7 /** 7 /**
8 * A class for working with a sequence of characters. 8 * A sequence of characters.
9 *
10 * A string can be either single or multiline. Single line strings are
sra1 2013/09/27 04:22:22 Wearing my pedant hat: A string itself if neither
11 * written using matching single or double quotes, and multiline strings are
12 * written using triple quotes. The following are all valid Dart strings:
13 *
14 * 'Single quotes';
15 * "Double quotes";
16 * 'Double quotes in "single" quotes';
17 * "Single quotes in 'double' quotes";
18 *
19 * '''A
20 * multiline
21 * string''';
22 *
23 * """
24 * Another
25 * multiline
26 * string""";
27 *
28 * Strings are immutable. Although you cannot change a string, you can perform
29 * an operation on a string and assign the result to a new string:
sra1 2013/09/27 04:22:22 You can't perform an operation 'on' a string becau
30 *
31 * var string = 'Dart is fun';
32 * var newString = string.substring(0, 5);
33 *
34 * You can use the plus (`+`) operator to concatenate strings:
35 *
36 * 'Dart ' + 'is ' + 'fun!'; // 'Dart is fun!'
37 *
38 * You can also use adjacent string literals for concatenation:
sra1 2013/09/27 04:22:22 This is not really a concatenation operation, it i
39 *
40 * 'Dart ' 'is ' 'fun!'; // 'Dart is fun!'
41 *
42 * You can use `${}` to interpolate the value of Dart expressions
43 * within strings. The curly braces can be omitted when evaluating identifiers:
44 *
45 * string = 'dartlang';
46 * '$string has ${string.length} letters'; // 'dartlang has 8 letters'
9 * 47 *
10 * A string is represented by a sequence of Unicode UTF-16 code units 48 * A string is represented by a sequence of Unicode UTF-16 code units
11 * accessible through the [codeUnitAt] or the [codeUnits] members. Their 49 * accessible through the [codeUnitAt] or the [codeUnits] members:
12 * string representation is accessible through the index-operator. 50 *
51 * string = 'Dart';
52 * string.codeUnitAt(0); // 68
53 * string.codeUnits; // [68, 97, 114, 116]
54 *
55 * The string representation of code units is accessible through the index
56 * operator:
57 *
58 * string[0]; // 'D'
13 * 59 *
14 * The characters of a string are encoded in UTF-16. Decoding UTF-16, which 60 * The characters of a string are encoded in UTF-16. Decoding UTF-16, which
15 * combines surrogate pairs, yields Unicode code points. Following a similar 61 * combines surrogate pairs, yields Unicode code points. Following a similar
16 * terminology to Go we use the name "rune" for an integer representing a 62 * terminology to Go, we use the name 'rune' for an integer representing a
17 * Unicode code point. The runes of a string are accessible through the [runes] 63 * Unicode code point. Use the [runes] property to get the runes of a string:
18 * getter.
19 * 64 *
20 * Strings are immutable. 65 * string.runes.toList(); // [68, 97, 114, 116]
21 * 66 *
22 * It is a compile-time error for a class to attempt to extend or implement 67 * For a character outside the Basic Multilingual Plane (plane 0) that is
23 * String. 68 * composed of a surrogate pair, [runes] combines the pair and returns a
69 * single integer. For example, the Unicode character for a
70 * musical G-clef ('𝄞') with rune value 0x1D11E consists of a UTF-16 surrogate
71 * pair: `0xD834` and `0xDD1E`. Using [codeUnits] returns the surrogate pair,
72 * and using `runes` returns their combined value:
24 * 73 *
25 * For concatenating strings efficiently, use the [StringBuffer] class. For 74 * var clef = '\u{1D11E}';
26 * working with regular expressions, use the [RegExp] class. 75 * clef.codeUnits; // [0xD834, 0xDD1E]
76 * clef.runes.toList(); // [0x1D11E]
77 *
78 * The String class can not be extended or implemented. Attempting to do so
79 * yields a compile-time error.
80 *
81 * ## Other resources
82 *
83 * See [StringBuffer] to efficiently build a string incrementally. See
84 * [RegExp] to work with regular expressions.
85 *
86 * Also see:
87
88 * * [Dart Cookbook](https://www.dartlang.org/docs/cookbook/#strings)
89 * for String examples and recipes.
90 * * [Dart Up and Running]
91 * (https://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html#ch03-st rings-and-regular-expressions)
27 */ 92 */
28 abstract class String implements Comparable<String>, Pattern { 93 abstract class String implements Comparable<String>, Pattern {
29 /** 94 /**
30 * Allocates a new String for the specified [charCodes]. 95 * Allocates a new String for the specified [charCodes].
31 * 96 *
32 * The [charCodes] can be UTF-16 code units or runes. If a char-code value is 97 * The [charCodes] can be UTF-16 code units or runes. If a char-code value is
33 * 16-bit it is copied verbatim. If it is greater than 16 bits it is 98 * 16-bit, it is copied verbatim:
34 * decomposed into a surrogate pair. 99 *
100 * new String.fromCharCodes([68]); // 'D'
101 *
102 * If a char-code value is greater than 16-bits, it is decomposed into a
103 * surrogate pair:
104 *
105 * var clef = new String.fromCharCodes([0x1D11E]);
106 * clef.codeUnitAt(0); // 0xD834
107 * clef.codeUnitAt(1); // 0xDD1E
35 */ 108 */
36 external factory String.fromCharCodes(Iterable<int> charCodes); 109 external factory String.fromCharCodes(Iterable<int> charCodes);
37 110
38 /** 111 /**
39 * Allocates a new String for the specified [charCode]. 112 * Allocates a new String for the specified [charCode].
40 * 113 *
41 * The new string contains a single code unit if the [charCode] can be 114 * If the [charCode] can be represented by a single UTF-16 code unit, the new
42 * represented by a single UTF-16 code unit. Otherwise the [length] is 2 and 115 * string contains a single code unit. Otherwise, the [length] is 2 and
43 * the code units form a surrogate pair. 116 * the code units form a surrogate pair. See documentation for
117 * [fromCharCodes].
44 * 118 *
45 * It is allowed (though generally discouraged) to create a String with only 119 * Creating a String with half of a surrogate pair is legal but generally
46 * one half of a surrogate pair. 120 * discouraged.
47 */ 121 */
48 factory String.fromCharCode(int charCode) { 122 factory String.fromCharCode(int charCode) {
49 List<int> charCodes = new List<int>.filled(1, charCode); 123 List<int> charCodes = new List<int>.filled(1, charCode);
50 return new String.fromCharCodes(charCodes); 124 return new String.fromCharCodes(charCodes);
51 } 125 }
52 126
53 /** 127 /**
54 * Gets the character (as a single-code-unit [String]) at the given [index]. 128 * Gets the character (as a single-code-unit [String]) at the given [index].
55 * 129 *
56 * The returned string represents exactly one UTF-16 code unit which may be 130 * The returned string represents exactly one UTF-16 code unit, which may be
57 * half of a surrogate pair. For example the Unicode character for a 131 * half of a surrogate pair. A single member of a surrogate pair is an
58 * musical G-clef ("𝄞") with rune value 0x1D11E consists of a UTF-16 surrogate 132 * invalid UTF-16 string:
59 * pair: `0xD834` and `0xDD1E`. Using the index-operator on this string yields
60 * a String with half of a surrogate pair:
61 * 133 *
62 * var clef = "\u{1D11E}"; 134 * var clef = '\u{1D11E}';
63 * clef.length; // => 2 135 * // These represent invalid UTF-16 strings.
64 * clef.runes.first == 0x1D11E; // => true 136 * clef[0].codeUnits; // [0xD834]
65 * clef.runes.length; // => 1 137 * clef[1].codeUnits; // [0xDD1E]
66 * clef.codeUnitAt(0); // => 0xD834
67 * clef.codeUnitAt(1); // => 0xDD1E
68 * // The following strings are halves of a UTF-16 surrogate pair and
69 * // thus invalid UTF-16 strings:
70 * clef[0]; // => a string of length 1 with code-unit value 0xD834.
71 * clef[1]; // => a string of length 1 with code-unit value 0xDD1E.
72 * 138 *
73 * This method is equivalent to 139 * This method is equivalent to
74 * `new String.fromCharCode(this.codeUnitAt(index))`. 140 * `new String.fromCharCode(this.codeUnitAt(index))`.
75 */ 141 */
76 String operator [](int index); 142 String operator [](int index);
77 143
78 /** 144 /**
79 * Returns the 16-bit UTF-16 code unit at the given [index]. 145 * Returns the 16-bit UTF-16 code unit at the given [index].
80 */ 146 */
81 int codeUnitAt(int index); 147 int codeUnitAt(int index);
82 148
83 /** 149 /**
84 * The length of the string. 150 * The length of the string.
85 * 151 *
86 * Returns the number of UTF-16 code units in this string. The number 152 * Returns the number of UTF-16 code units in this string. The number
87 * of [runes] might be less, if the string contains characters outside 153 * of [runes] might be fewer, if the string contains characters outside
88 * the basic multilingual plane (plane 0). 154 * the Basic Multilingual Plane (plane 0):
155 *
156 * 'Dart'.length; // 4
157 * 'Dart'.runes.length; // 4
158 *
159 * var clef = '\u{1D11E}';
160 * clef.length; // 2
161 * clef.runes.length; // 1
89 */ 162 */
90 int get length; 163 int get length;
91 164
92 /** 165 /**
93 * Returns whether the two strings are equal. 166 * Returns true if the two strings are equal. False, otherwise.
94 * 167 *
95 * This method compares each individual code unit of the strings. 168 * This method compares each individual code unit of the strings.
96 * Equivalently (for strings that are well-formed UTF-16) it compares each 169 * It does not check for Unicode equivalence.
97 * individual rune (code point). It does not check for Unicode equivalence. 170 * For example, both the following strings represent the string 'Amélie',
98 * For example the two following strings both represent the string "Amélie" 171 * but due to their different encoding, are not equal:
99 * but, due to their different encoding will not return equal.
100 * 172 *
101 * "Am\xe9lie" 173 * 'Am\xe9lie' == 'Ame\u{301}lie'; // false
102 * "Ame\u{301}lie"
103 * 174 *
104 * In the first string the "é" is encoded as a single unicode code unit (also 175 * The first string encodes 'é' as a single unicode code unit (also
105 * a single rune), whereas the second string encodes it as "e" with the 176 * a single rune), whereas the second string encodes it as 'e' with the
106 * combining accent character "◌́". 177 * combining accent character '◌́'.
107 */ 178 */
108 bool operator ==(var other); 179 bool operator ==(var other);
109 180
110 /** 181 /**
111 * Returns whether this string ends with [other]. 182 * Returns true if this string ends with [other]. For example:
183 *
184 * 'Dart'.endsWith('t'); // true
112 */ 185 */
113 bool endsWith(String other); 186 bool endsWith(String other);
114 187
115 /** 188 /**
116 * Returns whether this string starts with a match of [pattern]. 189 * Returns true if this string starts with a match of [pattern].
117 * 190 *
118 * If [index] is provided, instead check if the substring starting 191 * var string = 'Dart';
119 * at that index starts with a match of [pattern]. 192 * string.startsWith('D'); // true
193 * string.startsWith(new RegExp(r'[A-Z][a-z]')); // true
120 * 194 *
121 * It is an error if [index] is negative or greater than [length]. 195 * If [index] is provided, this method checks if the substring starting
196 * at that index starts with a match of [pattern]:
122 * 197 *
123 * A [RegExp] containing "^" will not match if the [index] is greater than 198 * string.startsWith('art', 1); // true
199 * string.startsWith(new RegExp(r'\w{3}')); // true
200 *
201 * [index] must not be negative or greater than [length].
202 *
203 * A [RegExp] containing '^' does not match if the [index] is greater than
124 * zero. The pattern works on the string as a whole, and does not extract 204 * zero. The pattern works on the string as a whole, and does not extract
125 * a substring starting at [index] first. That is. 205 * a substring starting at [index] first:
126 * "abc".startsWith(new RegExp("^.", 1)) == false 206 *
207 * string.startsWith(new RegExp(r'^art'), 1); // false
208 * string.startsWith(new RegExp(r'art'), 1); // true
127 */ 209 */
128 bool startsWith(Pattern pattern, [int index = 0]); 210 bool startsWith(Pattern pattern, [int index = 0]);
129 211
130 /** 212 /**
131 * Returns the first position of a match of [pattern] in this string, 213 * Returns the position of the first match of [pattern] in this string,
132 * starting at [start] (inclusive). 214 * starting at [start], inclusive:
133 * 215 *
134 * Returns -1 if a match could not be found. 216 * var string = 'Dartisans';
217 * string.indexOf('art'); // 1
218 * string.indexOf(new RegExp(r'[A-Z][a-z]')); // 0
135 * 219 *
136 * It is an error if start is negative or greater than [length]. 220 * Returns -1 if no match is found:
221 *
222 * string.indexOf(new RegExp(r'dart')); // -1
223 *
224 * [start] must not be negative or greater than [length].
137 */ 225 */
138 int indexOf(Pattern pattern, [int start]); 226 int indexOf(Pattern pattern, [int start]);
139 227
140 /** 228 /**
141 * Returns the last position of a match [pattern] in this string, searching 229 * Returns the position of the last match [pattern] in this string, searching
142 * backward starting at [start] (inclusive). 230 * backward starting at [start], inclusive:
231 *
232 * var string = 'Dartisans';
233 * string.lastIndexOf('a'); // 6
234 * string.lastIndexOf(new RegExp(r'a(r|n)')); // 6
143 * 235 *
144 * Returns -1 if [other] could not be found. 236 * Returns -1 if [other] could not be found.
145 * 237 *
146 * It is an error if start is negative or greater than [length]. 238 * string.lastIndexOf(new RegExp(r'DART')); // -1
239 *
240 * [start] must not be negative or greater than [length].
147 */ 241 */
148 int lastIndexOf(Pattern pattern, [int start]); 242 int lastIndexOf(Pattern pattern, [int start]);
149 243
150 /** 244 /**
151 * Returns whether this string is empty. 245 * Returns true if this string is empty.
152 */ 246 */
153 bool get isEmpty; 247 bool get isEmpty;
154 248
155 /** 249 /**
156 * Returns whether this string is not empty. 250 * Returns true if this string is not empty.
157 */ 251 */
158 bool get isNotEmpty; 252 bool get isNotEmpty;
159 253
160 /** 254 /**
161 * Creates a new string by concatenating this string with [other]. 255 * Creates a new string by concatenating this string with [other].
162 * 256 *
163 * A sequence of strings can be concatenated by using [Iterable.join]: 257 * 'dart' + 'lang'; // 'dartlang'
164 *
165 * var strings = ['foo', 'bar', 'geez'];
166 * var concatenated = strings.join();
167 */ 258 */
168 String operator +(String other); 259 String operator +(String other);
169 260
170 /** 261 /**
171 * Returns a substring of this string in the given range. 262 * Returns the substring of this string that extends from [startIndex],
172 * [startIndex] is inclusive and [endIndex] is exclusive. 263 * inclusive, to [endIndex], exclusive.
264 *
265 * var string = 'dartlang';
266 * string.substring(1); // 'artlang'
267 * string.substring(1, 4); // 'art'
173 */ 268 */
174 String substring(int startIndex, [int endIndex]); 269 String substring(int startIndex, [int endIndex]);
175 270
176 /** 271 /**
177 * Removes leading and trailing whitespace from a string. 272 * Removes leading and trailing whitespace from a string.
178 * 273 *
179 * If the string contains leading or trailing whitespace a new string with no 274 * If the string contains leading or trailing whitespace, a new string with no
180 * leading and no trailing whitespace is returned. Otherwise, the string 275 * leading and no trailing whitespace is returned:
181 * itself is returned. 276 *
277 * '\tDart is fun\n'.trim(); // 'Dart is fun'
278 *
279 * Otherwise, the original string itself is returned:
280 *
281 * var str1 = 'Dart';
282 * var str2 = str1.trim();
283 * identical(str1, str2); // true
182 * 284 *
183 * Whitespace is defined by the Unicode White_Space property (as defined in 285 * Whitespace is defined by the Unicode White_Space property (as defined in
184 * version 6.2 or later) and the BOM character, 0xFEFF. 286 * version 6.2 or later) and the BOM character, 0xFEFF.
185 * 287 *
186 * Here is the list of trimmed characters (following version 6.2): 288 * Here is the list of trimmed characters (following version 6.2):
187 * 289 *
188 * 0009..000D ; White_Space # Cc <control-0009>..<control-000D> 290 * 0009..000D ; White_Space # Cc <control-0009>..<control-000D>
189 * 0020 ; White_Space # Zs SPACE 291 * 0020 ; White_Space # Zs SPACE
190 * 0085 ; White_Space # Cc <control-0085> 292 * 0085 ; White_Space # Cc <control-0085>
191 * 00A0 ; White_Space # Zs NO-BREAK SPACE 293 * 00A0 ; White_Space # Zs NO-BREAK SPACE
192 * 1680 ; White_Space # Zs OGHAM SPACE MARK 294 * 1680 ; White_Space # Zs OGHAM SPACE MARK
193 * 180E ; White_Space # Zs MONGOLIAN VOWEL SEPARATOR 295 * 180E ; White_Space # Zs MONGOLIAN VOWEL SEPARATOR
194 * 2000..200A ; White_Space # Zs EN QUAD..HAIR SPACE 296 * 2000..200A ; White_Space # Zs EN QUAD..HAIR SPACE
195 * 2028 ; White_Space # Zl LINE SEPARATOR 297 * 2028 ; White_Space # Zl LINE SEPARATOR
196 * 2029 ; White_Space # Zp PARAGRAPH SEPARATOR 298 * 2029 ; White_Space # Zp PARAGRAPH SEPARATOR
197 * 202F ; White_Space # Zs NARROW NO-BREAK SPACE 299 * 202F ; White_Space # Zs NARROW NO-BREAK SPACE
198 * 205F ; White_Space # Zs MEDIUM MATHEMATICAL SPACE 300 * 205F ; White_Space # Zs MEDIUM MATHEMATICAL SPACE
199 * 3000 ; White_Space # Zs IDEOGRAPHIC SPACE 301 * 3000 ; White_Space # Zs IDEOGRAPHIC SPACE
200 * 302 *
201 * FEFF ; BOM ZERO WIDTH NO_BREAK SPACE 303 * FEFF ; BOM ZERO WIDTH NO_BREAK SPACE
202 */ 304 */
203 String trim(); 305 String trim();
204 306
205 /** 307 /**
206 * Returns whether this string contains a match of [other]. 308 * Returns true if this string contains a match of [other]:
207 * 309 *
208 * If [startIndex] is provided, only matches at or after that index 310 * var string = 'Dart strings';
209 * are considered. 311 * string.contains('D'); // true
312 * string.contains(new RegExp(r'[A-Z]')); // true
210 * 313 *
211 * It is an error if [startIndex] is negative or greater than [length]. 314 * If [startIndex] is provided, this method matches only at or after that
315 * index:
316 *
317 * string.contains('X', 1); // false
318 * string.contains(new RegExp(r'[A-Z]'), 1); // false
319 *
320 * [startIndex] must not be negative or greater than [length].
212 */ 321 */
213 bool contains(Pattern other, [int startIndex = 0]); 322 bool contains(Pattern other, [int startIndex = 0]);
214 323
215 /** 324 /**
216 * Returns a new string where the first occurence of [from] in this string 325 * Returns a new string in which the first occurence of [from] in this string
217 * is replaced with [to]. 326 * is replaced with [to]:
327 *
328 * '0.0001'.replaceFirst(new RegExp(r'0'), ''); // '.0001'
218 */ 329 */
219 String replaceFirst(Pattern from, String to); 330 String replaceFirst(Pattern from, String to);
220 331
221 /** 332 /**
222 * Replaces all substrings matching [from] with [replace]. 333 * Replaces all substrings that match [from] with [replace].
223 * 334 *
224 * Returns a new string where the non-overlapping substrings that match 335 * Returns a new string in which the non-overlapping substrings matching
225 * [from] (the ones iterated by `from.allMatches(thisString)`) are replaced 336 * [from] (the ones iterated by `from.allMatches(thisString)`) are replaced
226 * by the literal string [replace]. 337 * by the literal string [replace].
227 * 338 *
339 * 'resume'.replaceAll(new RegExp(r'e'), 'é'); // 'résumé'
340 *
228 * Notice that the [replace] string is not interpreted. If the replacement 341 * Notice that the [replace] string is not interpreted. If the replacement
229 * depends on the match (for example on a [RegExp]'s capture groups), use 342 * depends on the match (for example on a [RegExp]'s capture groups), use
230 * the [replaceAllMapped] method instead. 343 * the [replaceAllMapped] method instead.
231 */ 344 */
232 String replaceAll(Pattern from, String replace); 345 String replaceAll(Pattern from, String replace);
233 346
234 /** 347 /**
235 * Replace all substrings matching [from] by a string computed from the match. 348 * Replace all substrings that match [from] by a string computed from the
349 * match.
236 * 350 *
237 * Returns a new string where the non-overlapping substrings that match 351 * Returns a new string in which the non-overlapping substrings that match
238 * [from] (the ones iterated by `from.allMatches(thisString)`) are replaced 352 * [from] (the ones iterated by `from.allMatches(thisString)`) are replaced
239 * by the result of calling [replace] on the corresponding [Match] object. 353 * by the result of calling [replace] on the corresponding [Match] object.
240 * 354 *
241 * This can be used to replace matches with new content that depends on the 355 * This can be used to replace matches with new content that depends on the
242 * match, unlike [replaceAll] where the replacement string is always the same. 356 * match, unlike [replaceAll] where the replacement string is always the same.
243 * 357 *
244 * Example (simplified pig latin): 358 * The [replace] function is called with the [Match] generated
359 * by the pattern, and its result is used as replacement.
360 *
361 * The function defined below converts each word in a string to simplified
362 * 'pig latin' using [replaceAllMapped]:
363 *
245 * pigLatin(String words) => words.replaceAllMapped( 364 * pigLatin(String words) => words.replaceAllMapped(
246 * new RegExp(r"\b(\w*?)([aeiou]\w*)", caseSensitive: false), 365 * new RegExp(r'\b(\w*?)([aeiou]\w*)', caseSensitive: false),
247 * (Match m) => "${m[2]}${m[1]}${m[1].isEmpty ? 'way' : 'ay'}"); 366 * (Match m) => "${m[2]}${m[1]}${m[1].isEmpty ? 'way' : 'ay'}");
248 * 367 *
249 * This would convert each word of a text to "pig-latin", so for example 368 * pigLatin('I have a secret now!'); // 'Iway avehay away ecretsay ownay!'
250 * `pigLatin("I have a secret now!")`
251 * returns
252 * `"Iway avehay away ecretsay ownay!"`
253 */ 369 */
254 String replaceAllMapped(Pattern from, String replace(Match match)); 370 String replaceAllMapped(Pattern from, String replace(Match match));
255 371
256 /** 372 /**
257 * Splits the string around matches of [pattern]. Returns 373 * Splits the string at matches of [pattern]. Returns
258 * a list of substrings. 374 * a list of substrings.
259 * 375 *
260 * Splitting with an empty string pattern (`""`) splits at UTF-16 code unit 376 * Splitting with an empty string pattern (`''`) splits at UTF-16 code unit
261 * boundaries and not at rune boundaries. The following two expressions 377 * boundaries and not at rune boundaries:
262 * are hence equivalent:
263 * 378 *
264 * string.split("") 379 * var string = 'Pub';
265 * string.codeUnits.map((unit) => new String.fromCharCode(unit)) 380 * string.split(''); // ['P', 'u', 'b']
266 * 381 *
267 * Unless it guaranteed that the string is in the basic multilingual plane 382 * string.codeUnits.map((unit) {
268 * (meaning that each code unit represents a rune) it is often better to 383 * return new String.fromCharCode(unit);
269 * map the runes instead: 384 * }).toList(); // ['P', 'u', 'b']
270 * 385 *
271 * string.runes.map((rune) => new String.fromCharCode(rune)) 386 * // String made up of two code units, but one rune.
387 * string = '\u{1D11E}';
388 * string.split('').length; // 2
389 *
390 * You should [map] the runes unless you are certain that the string is in
391 * the basic multilingual plane (meaning that each code unit represents a
392 * rune):
393 *
394 * string.runes.map((rune) => new String.fromCharCode(rune));
272 */ 395 */
273 List<String> split(Pattern pattern); 396 List<String> split(Pattern pattern);
274 397
275 /** 398 /**
276 * Splits the string on the [pattern], then converts each part and each match. 399 * Splits the string, converts its parts, and combines them into a new
sra1 2013/09/27 04:22:22 Perhaps: Splits the string into parts, ...
400 * string.
277 * 401 *
278 * The pattern is used to split the string into parts and separating matches. 402 * [pattern] is used to split the string into parts and separating matches.
279 * 403 *
280 * Each match is converted to a string by calling [onMatch]. If [onMatch] 404 * Each match is converted to a string by calling [onMatch]. If [onMatch]
281 * is omitted, the matched string is used. 405 * is omitted, the matched string is used.
282 * 406 *
283 * Each non-matched part is converted by a call to [onNonMatch]. If 407 * Each non-matched part is converted by a call to [onNonMatch]. If
284 * [onNonMatch] is omitted, the non-matching part is used. 408 * [onNonMatch] is omitted, the non-matching part is used.
285 * 409 *
286 * Then all the converted parts are combined into the resulting string. 410 * Then all the converted parts are combined into the resulting string.
411 *
412 * 'Eats shoots leaves'.splitMapJoin((new RegExp(r'shoots')),
413 * onMatch: (m) => '${m.group(0)}',
414 * onNonMatch: (n) => '*'); // *shoots*
287 */ 415 */
288 String splitMapJoin(Pattern pattern, 416 String splitMapJoin(Pattern pattern,
289 {String onMatch(Match match), 417 {String onMatch(Match match),
290 String onNonMatch(String nonMatch)}); 418 String onNonMatch(String nonMatch)});
291 419
292 /** 420 /**
293 * Returns an unmodifiable list of the UTF-16 code units of this string. 421 * Returns an unmodifiable list of the UTF-16 code units of this string.
294 */ 422 */
295 List<int> get codeUnits; 423 List<int> get codeUnits;
296 424
297 /** 425 /**
298 * Returns an iterable of Unicode code-points of this string. 426 * Returns an [Iterable] of Unicode code-points of this string.
299 * 427 *
300 * If the string contains surrogate pairs, they will be combined and returned 428 * If the string contains surrogate pairs, they are combined and returned
301 * as one integer by this iterator. Unmatched surrogate halves are treated 429 * as one integer by this iterator. Unmatched surrogate halves are treated
302 * like valid 16-bit code-units. 430 * like valid 16-bit code-units.
303 */ 431 */
304 Runes get runes; 432 Runes get runes;
305 433
306 /** 434 /**
307 * If this string is not already all lower case, returns a new string 435 * Converts all characters in this string to lower case.
sra1 2013/09/27 04:22:22 This sounds like the string is modified.
308 * where all characters are made lower case. Returns [:this:] otherwise. 436 * If the string is already in all lower case, this method returns [:this:].
437 *
438 * 'ALPHABET'.toLowerCase(); // 'alphabet'
439 * 'abc'.toLowerCase(); // 'abc'
440 *
441 * This function uses the language independent Unicode mapping and thus only
442 * works in some languages.
309 */ 443 */
310 // TODO(floitsch): document better. (See EcmaScript for description). 444 // TODO(floitsch): document better. (See EcmaScript for description).
311 String toLowerCase(); 445 String toLowerCase();
312 446
313 /** 447 /**
314 * If this string is not already all upper case, returns a new string 448 * Converts all characters in this string to upper case.
315 * where all characters are made upper case. Returns [:this:] otherwise. 449 * If the string is already in all upper case, this method returns [:this:].
450 *
451 * 'alphabet'.toUpperCase(); // 'ALPHABET'
452 * 'ABC'.toUpperCase(); // 'ABC'
453 *
454 * This function uses the language independent Unicode mapping and thus only
455 * works in some languages.
316 */ 456 */
317 // TODO(floitsch): document better. (See EcmaScript for description). 457 // TODO(floitsch): document better. (See EcmaScript for description).
318 String toUpperCase(); 458 String toUpperCase();
319 } 459 }
320 460
321 /** 461 /**
322 * The runes (integer Unicode code points) of a [String]. 462 * The runes (integer Unicode code points) of a [String].
323 */ 463 */
324 class Runes extends IterableBase<int> { 464 class Runes extends IterableBase<int> {
325 final String string; 465 final String string;
326 Runes(this.string); 466 Runes(this.string);
327 467
328 RuneIterator get iterator => new RuneIterator(string); 468 RuneIterator get iterator => new RuneIterator(string);
329 469
330 int get last { 470 int get last {
331 if (string.length == 0) { 471 if (string.length == 0) {
332 throw new StateError("No elements."); 472 throw new StateError('No elements.');
333 } 473 }
334 int length = string.length; 474 int length = string.length;
335 int code = string.codeUnitAt(length - 1); 475 int code = string.codeUnitAt(length - 1);
336 if (_isTrailSurrogate(code) && string.length > 1) { 476 if (_isTrailSurrogate(code) && string.length > 1) {
337 int previousCode = string.codeUnitAt(length - 2); 477 int previousCode = string.codeUnitAt(length - 2);
338 if (_isLeadSurrogate(previousCode)) { 478 if (_isLeadSurrogate(previousCode)) {
339 return _combineSurrogatePair(previousCode, code); 479 return _combineSurrogatePair(previousCode, code);
340 } 480 }
341 } 481 }
342 return code; 482 return code;
(...skipping 51 matching lines...) Expand 10 before | Expand all | Expand 10 after
394 throw new RangeError.range(index, 0, string.length); 534 throw new RangeError.range(index, 0, string.length);
395 } 535 }
396 _checkSplitSurrogate(index); 536 _checkSplitSurrogate(index);
397 } 537 }
398 538
399 /** Throw an error if the index is in the middle of a surrogate pair. */ 539 /** Throw an error if the index is in the middle of a surrogate pair. */
400 void _checkSplitSurrogate(int index) { 540 void _checkSplitSurrogate(int index) {
401 if (index > 0 && index < string.length && 541 if (index > 0 && index < string.length &&
402 _isLeadSurrogate(string.codeUnitAt(index - 1)) && 542 _isLeadSurrogate(string.codeUnitAt(index - 1)) &&
403 _isTrailSurrogate(string.codeUnitAt(index))) { 543 _isTrailSurrogate(string.codeUnitAt(index))) {
404 throw new ArgumentError("Index inside surrogate pair: $index"); 544 throw new ArgumentError('Index inside surrogate pair: $index');
405 } 545 }
406 } 546 }
407 547
408 /** 548 /**
409 * Returns the starting position of the current rune in the string. 549 * Returns the starting position of the current rune in the string.
410 * 550 *
411 * Returns null if the [current] rune is null. 551 * Returns null if the [current] rune is null.
412 */ 552 */
413 int get rawIndex => (_position != _nextPosition) ? _position : null; 553 int get rawIndex => (_position != _nextPosition) ? _position : null;
414 554
(...skipping 94 matching lines...) Expand 10 before | Expand all | Expand 10 after
509 _position = position - 1; 649 _position = position - 1;
510 _currentCodePoint = _combineSurrogatePair(prevCodeUnit, codeUnit); 650 _currentCodePoint = _combineSurrogatePair(prevCodeUnit, codeUnit);
511 return true; 651 return true;
512 } 652 }
513 } 653 }
514 _position = position; 654 _position = position;
515 _currentCodePoint = codeUnit; 655 _currentCodePoint = codeUnit;
516 return true; 656 return true;
517 } 657 }
518 } 658 }
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698