final class StringOps extends AnyVal
Provides extension methods for strings.
Some of these methods treat strings as a plain collection of Chars without any regard for Unicode handling. Unless the user takes Unicode handling in to account or makes sure the strings don't require such handling, these methods may result in unpaired or invalidly paired surrogate code units.
- Source
- StringOps.scala
- Alphabetic
- By Inheritance
- StringOps
- AnyVal
- Any
- by any2stringadd
- by StringFormat
- by Ensuring
- by ArrowAssoc
- Hide All
- Show All
- Public
- Protected
Value Members
- final def !=(arg0: Any): Boolean
Test two objects for inequality.
Test two objects for inequality.
- returns
trueif !(this == that), false otherwise.
- Definition Classes
- Any
- final def ##: Int
Equivalent to
x.hashCodeexcept for boxed numeric types andnull.Equivalent to
x.hashCodeexcept for boxed numeric types andnull. For numerics, it returns a hash value which is consistent with value equality: if two value type instances compare as true, then ## will produce the same hash value for each of them. Fornullreturns a hashcode wherenull.hashCodethrows aNullPointerException.- returns
a hash value consistent with ==
- Definition Classes
- Any
- def *(n: Int): String
Return the current string concatenated
ntimes. - def +(other: String): String
- Implicit
- This member is added by an implicit conversion from StringOps toany2stringadd[StringOps] performed by method any2stringadd in scala.Predef.
- Definition Classes
- any2stringadd
- def ++(xs: String): String
Alias for
concat - def ++(suffix: IterableOnce[Char]): String
Alias for
concatAlias for
concat- Annotations
- @inline()
- def ++[B >: Char](suffix: Iterable[B]): immutable.IndexedSeq[B]
Alias for
concatAlias for
concat- Annotations
- @inline()
- def ++:(prefix: String): String
Alias for
prependedAllAlias for
prependedAll- Annotations
- @inline()
- def ++:[B >: Char](prefix: IterableOnce[B]): immutable.IndexedSeq[B]
Alias for
prependedAllAlias for
prependedAll- Annotations
- @inline()
- def +:(c: Char): String
Alias for
prependedAlias for
prepended- Annotations
- @inline()
- def +:[B >: Char](elem: B): immutable.IndexedSeq[B]
Alias for
prependedAlias for
prepended- Annotations
- @inline()
- def ->[B](y: B): (StringOps, B)
- Implicit
- This member is added by an implicit conversion from StringOps toArrowAssoc[StringOps] performed by method ArrowAssoc in scala.Predef.
- Definition Classes
- ArrowAssoc
- Annotations
- @inline()
- def :+(c: Char): String
Alias for
appendedAlias for
appended- Annotations
- @inline()
- def :+[B >: Char](elem: B): immutable.IndexedSeq[B]
Alias for
appendedAlias for
appended- Annotations
- @inline()
- def :++(suffix: String): String
Alias for
appendedAllAlias for
appendedAll- Annotations
- @inline()
- def :++[B >: Char](suffix: IterableOnce[B]): immutable.IndexedSeq[B]
Alias for
appendedAllAlias for
appendedAll- Annotations
- @inline()
- def <(that: String): Boolean
Returns true if
thisis less thanthat - def <=(that: String): Boolean
Returns true if
thisis less than or equal tothat. - final def ==(arg0: Any): Boolean
Test two objects for equality.
Test two objects for equality. The expression
x == thatis equivalent toif (x eq null) that eq null else x.equals(that).- returns
trueif the receiver object is equivalent to the argument;falseotherwise.
- Definition Classes
- Any
- def >(that: String): Boolean
Returns true if
thisis greater thanthat. - def >=(that: String): Boolean
Returns true if
thisis greater than or equal tothat. - final def addString(b: mutable.StringBuilder, start: String, sep: String, end: String): mutable.StringBuilder
Appends this string to a string builder using start, end and separator strings.
- final def addString(b: mutable.StringBuilder, sep: String): mutable.StringBuilder
Appends this string to a string builder using a separator string.
Appends this string to a string builder using a separator string.
- Annotations
- @inline()
- final def addString(b: mutable.StringBuilder): mutable.StringBuilder
Appends this string to a string builder.
Appends this string to a string builder.
- Annotations
- @inline()
- def appended(c: Char): String
A copy of the string with an element appended
- def appended[B >: Char](elem: B): immutable.IndexedSeq[B]
A copy of the string with an element appended
- def appendedAll(suffix: String): String
A copy of the string with another string appended
A copy of the string with another string appended
- Annotations
- @inline()
- def appendedAll[B >: Char](suffix: IterableOnce[B]): immutable.IndexedSeq[B]
A copy of the string with all elements from a collection appended
A copy of the string with all elements from a collection appended
- Annotations
- @inline()
- def apply(i: Int): Char
Get the char at the specified index.
Get the char at the specified index.
- Annotations
- @inline()
- final def asInstanceOf[T0]: T0
Cast the receiver object to be of type
T0.Cast the receiver object to be of type
T0.Note that the success of a cast at runtime is modulo Scala's erasure semantics. Therefore the expression
1.asInstanceOf[String]will throw aClassCastExceptionat runtime, while the expressionList(1).asInstanceOf[List[String]]will not. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the requested type.- returns
the receiver object.
- Definition Classes
- Any
- Exceptions thrown
ClassCastExceptionif the receiver object is not an instance of the erasure of typeT0.
- def capitalize: String
Returns this string with first character converted to upper case.
Returns this string with first character converted to upper case. If the first character of the string is capitalized, it is returned unchanged. This method does not convert characters outside the Basic Multilingual Plane (BMP).
- def charStepper: IntStepper with EfficientSplit
Steps over characters in this string.
Steps over characters in this string. Values are packed in
Intfor efficiency and compatibility with Java 8 Streams which have an efficient specialization forInt.- Annotations
- @inline()
- def codePointStepper: IntStepper with EfficientSplit
Steps over code points in this string.
Steps over code points in this string.
- Annotations
- @inline()
- def collect[B](pf: PartialFunction[Char, B]): immutable.IndexedSeq[B]
Builds a new collection by applying a partial function to all chars of this String on which the function is defined.
Builds a new collection by applying a partial function to all chars of this String on which the function is defined.
- B
the element type of the returned collection.
- pf
the partial function which filters and maps the String.
- returns
a new collection resulting from applying the given partial function
pfto each char on which it is defined and collecting the results.
- def collect(pf: PartialFunction[Char, Char]): String
Builds a new String by applying a partial function to all chars of this String on which the function is defined.
Builds a new String by applying a partial function to all chars of this String on which the function is defined.
- pf
the partial function which filters and maps the String.
- returns
a new String resulting from applying the given partial function
pfto each char on which it is defined and collecting the results.
- def combinations(n: Int): Iterator[String]
Iterates over combinations.
Iterates over combinations. A _combination_ of length
nis a subsequence of the original string, with the chars taken in order. Thus,"xy"and"yy"are both length-2 combinations of"xyy", but"yx"is not. If there is more than one way to generate the same subsequence, only one will be returned.For example,
"xyyy"has three different ways to generate"xy"depending on whether the first, second, or third"y"is selected. However, since all are identical, only one will be chosen. Which of the three will be taken is an implementation detail that is not defined.- returns
An Iterator which traverses the possible n-element combinations of this string.
"abbbc".combinations(2) = Iterator(ab, ac, bb, bc)- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
Example: - def compare(that: String): Int
- def concat(suffix: String): String
Returns a new string containing the chars from this string followed by the chars from the right hand operand.
Returns a new string containing the chars from this string followed by the chars from the right hand operand.
- suffix
the string to append.
- returns
a new string which contains all chars of this string followed by all chars of
suffix.
- Annotations
- @inline()
- def concat(suffix: IterableOnce[Char]): String
Returns a new string containing the chars from this string followed by the chars from the right hand operand.
Returns a new string containing the chars from this string followed by the chars from the right hand operand.
- suffix
the collection to append.
- returns
a new string which contains all chars of this string followed by all chars of
suffix.
- def concat[B >: Char](suffix: IterableOnce[B]): immutable.IndexedSeq[B]
Returns a new collection containing the chars from this string followed by the elements from the right hand operand.
Returns a new collection containing the chars from this string followed by the elements from the right hand operand.
- suffix
the collection to append.
- returns
a new collection which contains all chars of this string followed by all elements of
suffix.
- def contains(elem: Char): Boolean
Tests whether this string contains the given character.
Tests whether this string contains the given character.
- elem
the character to test.
- returns
trueif this string has an element that is equal (as determined by==) toelem,falseotherwise.
- def copyToArray(xs: Array[Char], start: Int, len: Int): Int
Copy chars of this string to an array.
Copy chars of this string to an array. Fills the given array
xsstarting at indexstartwith at mostlenchars. Copying will stop once either the entire string has been copied, or the end of the array is reached orlenchars have been copied.- xs
the array to fill.
- start
the starting index.
- len
the maximal number of elements to copy.
- def copyToArray(xs: Array[Char], start: Int): Int
Copy chars of this string to an array.
Copy chars of this string to an array. Fills the given array
xsstarting at indexstart. Copying will stop once either the entire string has been copied or the end of the array is reached- xs
the array to fill.
- start
the starting index.
- Annotations
- @inline()
- def copyToArray(xs: Array[Char]): Int
Copy chars of this string to an array.
Copy chars of this string to an array. Fills the given array
xsstarting at index 0. Copying will stop once either the entire string has been copied or the end of the array is reached- xs
the array to fill.
- Annotations
- @inline()
- def count(p: (Char) => Boolean): Int
Counts the number of chars in this string which satisfy a predicate
- def diff[B >: Char](that: Seq[B]): String
Computes the multiset difference between this string and another sequence.
Computes the multiset difference between this string and another sequence.
- that
the sequence of chars to remove
- returns
a new string which contains all chars of this string except some of occurrences of elements that also appear in
that. If an element valuexappears n times inthat, then the first n occurrences ofxwill not form part of the result, but any following occurrences will.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def distinct: String
Selects all distinct chars of this string ignoring the duplicates.
Selects all distinct chars of this string ignoring the duplicates.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def distinctBy[B](f: (Char) => B): String
Selects all distinct chars of this string ignoring the duplicates as determined by
==after applying the transforming functionf.Selects all distinct chars of this string ignoring the duplicates as determined by
==after applying the transforming functionf.- B
the type of the elements after being transformed by
f- f
The transforming function whose result is used to determine the uniqueness of each element
- returns
a new string consisting of all the chars of this string without duplicates.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def drop(n: Int): String
The rest of the string without its
nfirst chars.The rest of the string without its
nfirst chars.- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def dropRight(n: Int): String
The rest of the string without its
nlast chars.The rest of the string without its
nlast chars.- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def dropWhile(p: (Char) => Boolean): String
Drops longest prefix of chars that satisfy a predicate.
Drops longest prefix of chars that satisfy a predicate.
- p
The predicate used to test elements.
- returns
the longest suffix of this string whose first element does not satisfy the predicate
p.
- def ensuring(cond: (StringOps) => Boolean, msg: => Any): StringOps
- Implicit
- This member is added by an implicit conversion from StringOps toEnsuring[StringOps] performed by method Ensuring in scala.Predef.
- Definition Classes
- Ensuring
- def ensuring(cond: (StringOps) => Boolean): StringOps
- Implicit
- This member is added by an implicit conversion from StringOps toEnsuring[StringOps] performed by method Ensuring in scala.Predef.
- Definition Classes
- Ensuring
- def ensuring(cond: Boolean, msg: => Any): StringOps
- Implicit
- This member is added by an implicit conversion from StringOps toEnsuring[StringOps] performed by method Ensuring in scala.Predef.
- Definition Classes
- Ensuring
- def ensuring(cond: Boolean): StringOps
- Implicit
- This member is added by an implicit conversion from StringOps toEnsuring[StringOps] performed by method Ensuring in scala.Predef.
- Definition Classes
- Ensuring
- def exists(p: (Char) => Boolean): Boolean
Tests whether a predicate holds for at least one char of this string.
- def filter(pred: (Char) => Boolean): String
Selects all chars of this string which satisfy a predicate.
- def filterNot(pred: (Char) => Boolean): String
Selects all chars of this string which do not satisfy a predicate.
Selects all chars of this string which do not satisfy a predicate.
- Annotations
- @inline()
- def find(p: (Char) => Boolean): Option[Char]
Finds the first char of the string satisfying a predicate, if any.
Finds the first char of the string satisfying a predicate, if any.
- p
the predicate used to test elements.
- returns
an option value containing the first element in the string that satisfies
p, orNoneif none exists.
- def flatMap(f: (Char) => String): String
Builds a new string by applying a function to all chars of this string and using the elements of the resulting strings.
Builds a new string by applying a function to all chars of this string and using the elements of the resulting strings.
- f
the function to apply to each char.
- returns
a new string resulting from applying the given string-valued function
fto each char of this string and concatenating the results.
- def flatMap[B](f: (Char) => IterableOnce[B]): immutable.IndexedSeq[B]
Builds a new collection by applying a function to all chars of this string and using the elements of the resulting collections.
Builds a new collection by applying a function to all chars of this string and using the elements of the resulting collections.
- f
the function to apply to each char.
- returns
a new collection resulting from applying the given collection-valued function
fto each char of this string and concatenating the results.
- def fold[A1 >: Char](z: A1)(op: (A1, A1) => A1): A1
Folds the chars of this string using the specified associative binary operator.
Folds the chars of this string using the specified associative binary operator.
- A1
a type parameter for the binary operator, a supertype of Char.
- z
a neutral element for the fold operation; may be added to the result an arbitrary number of times, and must not change the result (e.g.,
Nilfor list concatenation, 0 for addition, or 1 for multiplication).- op
a binary operator that must be associative.
- returns
the result of applying the fold operator
opbetween all the chars andz, orzif this string is empty.
- Annotations
- @inline()
- def foldLeft[B](z: B)(op: (B, Char) => B): B
Applies a binary operator to a start value and all chars of this string, going left to right.
Applies a binary operator to a start value and all chars of this string, going left to right.
- B
the result type of the binary operator.
- z
the start value.
- op
the binary operator.
- returns
the result of inserting
opbetween consecutive chars of this string, going left to right with the start valuezon the left:op(...op(z, x_1), x_2, ..., x_n)
where
x1, ..., xnare the chars of this string. Returnszif this string is empty.
- def foldRight[B](z: B)(op: (Char, B) => B): B
Applies a binary operator to all chars of this string and a start value, going right to left.
Applies a binary operator to all chars of this string and a start value, going right to left.
- B
the result type of the binary operator.
- z
the start value.
- op
the binary operator.
- returns
the result of inserting
opbetween consecutive chars of this string, going right to left with the start valuezon the right:op(x_1, op(x_2, ... op(x_n, z)...))
where
x1, ..., xnare the chars of this string. Returnszif this string is empty.
- def forall(p: (Char) => Boolean): Boolean
Tests whether a predicate holds for all chars of this string.
Tests whether a predicate holds for all chars of this string.
- p
the predicate used to test elements.
- returns
trueif this string is empty or the given predicatepholds for all chars of this string, otherwisefalse.
- def foreach[U](f: (Char) => U): Unit
Apply
fto each element for its side effects.Apply
fto each element for its side effects. Note: [U] parameter needed to help scalac's type inference. - def format(args: Any*): String
Uses the underlying string as a pattern (in a fashion similar to printf in C), and uses the supplied arguments to fill in the holes.
Uses the underlying string as a pattern (in a fashion similar to printf in C), and uses the supplied arguments to fill in the holes.
The interpretation of the formatting patterns is described in java.util.Formatter, with the addition that classes deriving from
ScalaNumber(such as scala.BigInt and scala.BigDecimal) are unwrapped to pass a type whichFormatterunderstands.- args
the arguments used to instantiating the pattern.
- Exceptions thrown
- def formatLocal(l: Locale, args: Any*): String
Like
format(args*)but takes an initialLocaleparameter which influences formatting as injava.lang.String's format.Like
format(args*)but takes an initialLocaleparameter which influences formatting as injava.lang.String's format.The interpretation of the formatting patterns is described in java.util.Formatter, with the addition that classes deriving from
ScalaNumber(such asscala.BigIntandscala.BigDecimal) are unwrapped to pass a type whichFormatterunderstands.- l
an instance of
java.util.Locale- args
the arguments used to instantiating the pattern.
- Exceptions thrown
- def getClass(): Class[_ <: AnyVal]
Returns the runtime class representation of the object.
- def groupBy[K](f: (Char) => K): immutable.Map[K, String]
Partitions this string into a map of strings according to some discriminator function.
Partitions this string into a map of strings according to some discriminator function.
- K
the type of keys returned by the discriminator function.
- f
the discriminator function.
- returns
A map from keys to strings such that the following invariant holds:
(xs groupBy f)(k) = xs filter (x => f(x) == k)That is, every key
kis bound to a string of those elementsxfor whichf(x)equalsk.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def grouped(size: Int): Iterator[String]
Partitions elements in fixed size strings.
Partitions elements in fixed size strings.
- size
the number of elements per group
- returns
An iterator producing strings of size
size, except the last will be less than sizesizeif the elements don't divide evenly.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- See also
scala.collection.Iterator, method
grouped
- def head: Char
Selects the first char of this string.
Selects the first char of this string.
- returns
the first char of this string.
- Exceptions thrown
NoSuchElementExceptionif the string is empty.
- def headOption: Option[Char]
Optionally selects the first char.
Optionally selects the first char.
- returns
the first char of this string if it is nonempty,
Noneif it is empty.
- def indexWhere(p: (Char) => Boolean, from: Int = 0): Int
Finds index of the first char satisfying some predicate after or at some start index.
Finds index of the first char satisfying some predicate after or at some start index.
- p
the predicate used to test elements.
- from
the start index
- returns
the index
>= fromof the first element of this string that satisfies the predicatep, or-1, if none exists.
- def indices: Range
Produces the range of all indices of this string.
Produces the range of all indices of this string.
- returns
a
Rangevalue from0to one less than the length of this string.
- def init: String
The initial part of the string without its last char.
The initial part of the string without its last char.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def inits: Iterator[String]
Iterates over the inits of this string.
Iterates over the inits of this string. The first value will be this string and the final one will be an empty string, with the intervening values the results of successive applications of
init.- returns
an iterator over all the inits of this string
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def intersect[B >: Char](that: Seq[B]): String
Computes the multiset intersection between this string and another sequence.
Computes the multiset intersection between this string and another sequence.
- that
the sequence of chars to intersect with.
- returns
a new string which contains all chars of this string which also appear in
that. If an element valuexappears n times inthat, then the first n occurrences ofxwill be retained in the result, but any following occurrences will be omitted.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- final def isInstanceOf[T0]: Boolean
Test whether the dynamic type of the receiver object has the same erasure as
T0.Test whether the dynamic type of the receiver object has the same erasure as
T0.Depending on what
T0is, the test is done in one of the below ways:T0is a non-parameterized class type, e.g.BigDecimal: this method returnstrueif the value of the receiver object is aBigDecimalor a subtype ofBigDecimal.T0is a parameterized class type, e.g.List[Int]: this method returnstrueif the value of the receiver object is someList[X]for anyX. For example,List(1, 2, 3).isInstanceOf[List[String]]will return true.T0is some singleton typex.typeor literalx: this method returnsthis.eq(x). For example,x.isInstanceOf[1]is equivalent tox.eq(1)T0is an intersectionX with YorX & Y: this method is equivalent tox.isInstanceOf[X] && x.isInstanceOf[Y]T0is a unionX | Y: this method is equivalent tox.isInstanceOf[X] || x.isInstanceOf[Y]T0is a type parameter or an abstract type member: this method is equivalent toisInstanceOf[U]whereUisT0's upper bound,AnyifT0is unbounded. For example,x.isInstanceOf[A]whereAis an unbounded type parameter will return true for any value ofx.
This is exactly equivalent to the type pattern
_: T0- returns
trueif the receiver object is an instance of erasure of typeT0;falseotherwise.
- Definition Classes
- Any
- Note
due to the unexpectedness of
List(1, 2, 3).isInstanceOf[List[String]]returning true andx.isInstanceOf[A]whereAis a type parameter or abstract member returning true, these forms issue a warning.
- def iterator: Iterator[Char]
Iterator can be used only once
- def knownSize: Int
- Annotations
- @inline()
- def last: Char
Selects the last char of this string.
Selects the last char of this string.
- returns
the last char of this string.
- Exceptions thrown
NoSuchElementExceptionif the string is empty.
- def lastIndexWhere(p: (Char) => Boolean, end: Int = Int.MaxValue): Int
Finds index of the last char satisfying some predicate before or at some end index.
Finds index of the last char satisfying some predicate before or at some end index.
- p
the predicate used to test elements.
- end
the end index
- returns
the index
<= endof the last element of this string that satisfies the predicatep, or-1, if none exists.
- def lastOption: Option[Char]
Optionally selects the last char.
Optionally selects the last char.
- returns
the last char of this string if it is nonempty,
Noneif it is empty.
- def lazyZip[B](that: Iterable[B]): LazyZip2[Char, B, String]
Analogous to
zipexcept that the elements in each collection are not consumed until a strict operation is invoked on the returnedLazyZip2decorator.Analogous to
zipexcept that the elements in each collection are not consumed until a strict operation is invoked on the returnedLazyZip2decorator.Calls to
lazyZipcan be chained to support higher arities (up to 4) without incurring the expense of constructing and deconstructing intermediary tuples.val xs = List(1, 2, 3) val res = (xs lazyZip xs lazyZip xs lazyZip xs).map((a, b, c, d) => a + b + c + d) // res == List(4, 8, 12)
- B
the type of the second element in each eventual pair
- that
the iterable providing the second element of each eventual pair
- returns
a decorator
LazyZip2that allows strict operations to be performed on the lazily evaluated pairs or chained calls tolazyZip. Implicit conversion toIterable[(A, B)]is also supported.
- def lengthCompare(len: Int): Int
- def lengthIs: Int
- def linesIterator: Iterator[String]
Lines in this string, where a line is terminated by
"\n","\r","\r\n", or the end of the string.Lines in this string, where a line is terminated by
"\n","\r","\r\n", or the end of the string. A line may be empty. Line terminators are removed. - def linesWithSeparators: Iterator[String]
Return an iterator of all lines embedded in this string, including trailing line separator characters.
Return an iterator of all lines embedded in this string, including trailing line separator characters.
The empty string yields an empty iterator.
- def map(f: (Char) => Char): String
Builds a new string by applying a function to all chars of this string.
Builds a new string by applying a function to all chars of this string.
- f
the function to apply to each char.
- returns
a new string resulting from applying the given function
fto each char of this string and collecting the results.
- def map[B](f: (Char) => B): immutable.IndexedSeq[B]
Builds a new collection by applying a function to all chars of this string.
Builds a new collection by applying a function to all chars of this string.
- f
the function to apply to each char.
- returns
a new collection resulting from applying the given function
fto each char of this string and collecting the results.
- final def mkString: String
Returns this string
Returns this string
- Annotations
- @inline()
- final def mkString(sep: String): String
Displays all elements of this string in a string using a separator string.
Displays all elements of this string in a string using a separator string.
- sep
the separator string.
- returns
In the resulting string the chars of this string are separated by the string
sep.
- Annotations
- @inline()
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- final def mkString(start: String, sep: String, end: String): String
Displays all elements of this string in a string using start, end, and separator strings.
Displays all elements of this string in a string using start, end, and separator strings.
- start
the starting string.
- sep
the separator string.
- end
the ending string.
- returns
The resulting string begins with the string
startand ends with the stringend. Inside, the string chars of this string are separated by the stringsep.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def nonEmpty: Boolean
Tests whether the string is not empty.
Tests whether the string is not empty.
- Annotations
- @inline()
- def padTo(len: Int, elem: Char): String
Returns a string with a char appended until a given target length is reached.
Returns a string with a char appended until a given target length is reached.
- len
the target length
- elem
the padding value
- returns
a string consisting of this string followed by the minimal number of occurrences of
elemso that the resulting string has a length of at leastlen.
- def padTo[B >: Char](len: Int, elem: B): immutable.IndexedSeq[B]
Returns a collection with an element appended until a given target length is reached.
Returns a collection with an element appended until a given target length is reached.
- len
the target length
- elem
the padding value
- returns
a collection consisting of this string followed by the minimal number of occurrences of
elemso that the resulting collection has a length of at leastlen.
- def partition(p: (Char) => Boolean): (String, String)
A pair of, first, all chars that satisfy predicate
pand, second, all chars that do not. - def partitionMap(f: (Char) => Either[Char, Char]): (String, String)
Applies a function
fto each character of the string and returns a pair of strings: the first one made of those characters returned byfthat were wrapped in scala.util.Left, and the second one made of those wrapped in scala.util.Right.Applies a function
fto each character of the string and returns a pair of strings: the first one made of those characters returned byfthat were wrapped in scala.util.Left, and the second one made of those wrapped in scala.util.Right.Example:
val xs = "1one2two3three" partitionMap { c => if (c > 'a') Left(c) else Right(c) } // xs == ("onetwothree", "123")
- f
the 'split function' mapping the elements of this string to an scala.util.Either
- returns
a pair of strings: the first one made of those characters returned by
fthat were wrapped in scala.util.Left, and the second one made of those wrapped in scala.util.Right.
- def patch(from: Int, other: String, replaced: Int): String
Produces a new string where a slice of characters in this string is replaced by another string.
Produces a new string where a slice of characters in this string is replaced by another string.
Patching at negative indices is the same as patching starting at 0. Patching at indices at or larger than the length of the original string appends the patch to the end. If more values are replaced than actually exist, the excess is ignored.
- from
the index of the first replaced char
- other
the replacement string
- replaced
the number of chars to drop in the original string
- returns
a new string consisting of all chars of this string except that
replacedchars starting fromfromare replaced byother.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def patch(from: Int, other: IterableOnce[Char], replaced: Int): String
Produces a new collection where a slice of characters in this string is replaced by another collection.
Produces a new collection where a slice of characters in this string is replaced by another collection.
Patching at negative indices is the same as patching starting at 0. Patching at indices at or larger than the length of the original string appends the patch to the end. If more values are replaced than actually exist, the excess is ignored.
- from
the index of the first replaced char
- other
the replacement string
- replaced
the number of chars to drop in the original string
- returns
a new string consisting of all chars of this string except that
replacedchars starting fromfromare replaced byother.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def patch[B >: Char](from: Int, other: IterableOnce[B], replaced: Int): immutable.IndexedSeq[B]
Produces a new collection where a slice of characters in this string is replaced by another collection.
Produces a new collection where a slice of characters in this string is replaced by another collection.
Patching at negative indices is the same as patching starting at 0. Patching at indices at or larger than the length of the original string appends the patch to the end. If more values are replaced than actually exist, the excess is ignored.
- from
the index of the first replaced char
- other
the replacement collection
- replaced
the number of chars to drop in the original string
- returns
a new collection consisting of all chars of this string except that
replacedchars starting fromfromare replaced byother.
- def permutations: Iterator[String]
Iterates over distinct permutations.
Iterates over distinct permutations.
- returns
An Iterator which traverses the distinct permutations of this string.
"abb".permutations = Iterator(abb, bab, bba)- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
Example: - def prepended(c: Char): String
A copy of the string with an char prepended
- def prepended[B >: Char](elem: B): immutable.IndexedSeq[B]
A copy of the string with an element prepended
- def prependedAll(prefix: String): String
A copy of the string with another string prepended
- def prependedAll[B >: Char](prefix: IterableOnce[B]): immutable.IndexedSeq[B]
A copy of the string with all elements from a collection prepended
- def r: Regex
You can follow a string with
.r, turning it into aRegex.You can follow a string with
.r, turning it into aRegex. E.g."""A\w*""".ris the regular expression for ASCII-only identifiers starting withA."""(?<month>\d\d)-(?<day>\d\d)-(?<year>\d\d\d\d)""".rmatches dates and provides its subcomponents through groups named "month", "day" and "year". - def reverse: String
Returns new sequence with elements in reversed order.
Returns new sequence with elements in reversed order.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def reverseIterator: Iterator[Char]
An iterator yielding chars in reversed order.
An iterator yielding chars in reversed order.
Note:
xs.reverseIteratoris the same asxs.reverse.iteratorbut implemented more efficiently.- returns
an iterator yielding the chars of this string in reversed order
- def size: Int
- Annotations
- @inline()
- def sizeCompare(otherSize: Int): Int
- def sizeIs: Int
- def slice(from: Int, until: Int): String
Selects an interval of elements.
Selects an interval of elements. The returned string is made up of all elements
xwhich satisfy the invariant:from <= indexOf(x) < until
- from
the lowest index to include from this string.
- until
the lowest index to EXCLUDE from this string.
- returns
a string containing the elements greater than or equal to index
fromextending up to (but not including) indexuntilof this string.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def sliding(size: Int, step: Int = 1): Iterator[String]
Groups chars in fixed size blocks by passing a "sliding window" over them (as opposed to partitioning them, as is done in grouped.)
Groups chars in fixed size blocks by passing a "sliding window" over them (as opposed to partitioning them, as is done in grouped.)
- size
the number of chars per group
- step
the distance between the first chars of successive groups
- returns
An iterator producing strings of size
size, except the last element (which may be the only element) will be truncated if there are fewer thansizechars remaining to be grouped.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- See also
scala.collection.Iterator, method
sliding
- def sortBy[B](f: (Char) => B)(implicit ord: Ordering[B]): String
Sorts this string according to the Ordering which results from transforming an implicitly given Ordering with a transformation function.
Sorts this string according to the Ordering which results from transforming an implicitly given Ordering with a transformation function.
The sort is stable. That is, elements that are equal (as determined by
ord.compare) appear in the same order in the sorted sequence as in the original.- B
the target type of the transformation
f, and the type where the orderingordis defined.- f
the transformation function mapping elements to some other domain
B.- ord
the ordering assumed on domain
B.- returns
a string consisting of the chars of this string sorted according to the ordering where
x < yiford.lt(f(x), f(y)).
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- See also
- def sortWith(lt: (Char, Char) => Boolean): String
Sorts this string according to a comparison function.
Sorts this string according to a comparison function.
The sort is stable. That is, elements that are equal (as determined by
lt) appear in the same order in the sorted sequence as in the original.- lt
the comparison function which tests whether its first argument precedes its second argument in the desired ordering.
- returns
a string consisting of the elements of this string sorted according to the comparison function
lt.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def sorted[B >: Char](implicit ord: Ordering[B]): String
Sorts the characters of this string according to an Ordering.
Sorts the characters of this string according to an Ordering.
The sort is stable. That is, elements that are equal (as determined by
ord.compare) appear in the same order in the sorted sequence as in the original.- ord
the ordering to be used to compare elements.
- returns
a string consisting of the chars of this string sorted according to the ordering
ord.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- See also
- def span(p: (Char) => Boolean): (String, String)
Splits this string into a prefix/suffix pair according to a predicate.
Splits this string into a prefix/suffix pair according to a predicate.
Note:
c span pis equivalent to (but more efficient than)(c takeWhile p, c dropWhile p), provided the evaluation of the predicatepdoes not cause any side-effects.- p
the test predicate
- returns
a pair consisting of the longest prefix of this string whose chars all satisfy
p, and the rest of this string.
- def split(separators: Array[Char]): Array[String]
- Annotations
- @throws(clazz = classOf[java.util.regex.PatternSyntaxException])
- def split(separator: Char): Array[String]
Split this string around the separator character
Split this string around the separator character
If this string is the empty string, returns an array of strings that contains a single empty string.
If this string is not the empty string, returns an array containing the substrings terminated by the start of the string, the end of the string or the separator character, excluding empty trailing substrings
If the separator character is a surrogate character, only split on matching surrogate characters if they are not part of a surrogate pair
The behaviour follows, and is implemented in terms of String.split(re: String)
- separator
the character used as a delimiter
"a.b".split('.') //returns Array("a", "b") //splitting the empty string always returns the array with a single //empty string "".split('.') //returns Array("") //only trailing empty substrings are removed "a.".split('.') //returns Array("a") ".a.".split('.') //returns Array("", "a") "..a..".split('.') //returns Array("", "", "a") //all parts are empty and trailing ".".split('.') //returns Array() "..".split('.') //returns Array() //surrogate pairs val high = 0xD852.toChar val low = 0xDF62.toChar val highstring = high.toString val lowstring = low.toString //well-formed surrogate pairs are not split val highlow = highstring + lowstring highlow.split(high) //returns Array(highlow) //bare surrogate characters are split val bare = "_" + highstring + "_" bare.split(high) //returns Array("_", "_")
Example: - def splitAt(n: Int): (String, String)
Splits this string into two at a given position.
Splits this string into two at a given position. Note:
c splitAt nis equivalent to(c take n, c drop n).- n
the position at which to split.
- returns
a pair of strings consisting of the first
nchars of this string, and the other chars.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def stepper: IntStepper with EfficientSplit
Stepper can be used with Java 8 Streams.
Stepper can be used with Java 8 Streams. This method is equivalent to a call to charStepper. See also codePointStepper.
- Annotations
- @inline()
- def stripLineEnd: String
Strip the trailing line separator from this string if there is one.
Strip the trailing line separator from this string if there is one. The line separator is taken as
"\n","\r", or"\r\n". - def stripMargin: String
For every line in this string:
For every line in this string:
Strip a leading prefix consisting of blanks or control characters followed by
|from the line. - def stripMargin(marginChar: Char): String
For every line in this string:
For every line in this string:
Strip a leading prefix consisting of blanks or control characters followed by
marginCharfrom the line. - def stripPrefix(prefix: String): String
Returns this string with the given
prefixstripped.Returns this string with the given
prefixstripped. If this string does not start withprefix, it is returned unchanged. - def stripSuffix(suffix: String): String
Returns this string with the given
suffixstripped.Returns this string with the given
suffixstripped. If this string does not end withsuffix, it is returned unchanged. - def tail: String
The rest of the string without its first char.
The rest of the string without its first char.
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def tails: Iterator[String]
Iterates over the tails of this string.
Iterates over the tails of this string. The first value will be this string and the final one will be an empty string, with the intervening values the results of successive applications of
tail.- returns
an iterator over all the tails of this string
- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def take(n: Int): String
A string containing the first
nchars of this string.A string containing the first
nchars of this string.- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def takeRight(n: Int): String
A string containing the last
nchars of this string.A string containing the last
nchars of this string.- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def takeWhile(p: (Char) => Boolean): String
Takes longest prefix of chars that satisfy a predicate.
- def toArray[B >: Char](implicit tag: ClassTag[B]): Array[B]
- def toBoolean: Boolean
- Exceptions thrown
java.lang.IllegalArgumentExceptionIf the string does not contain a parsableBoolean.
- def toBooleanOption: Option[Boolean]
Try to parse as a
BooleanTry to parse as a
Boolean- returns
Some(true)if the string is "true" case insensitive,Some(false)if the string is "false" case insensitive, andNoneif the string is anything else
- Exceptions thrown
java.lang.NullPointerExceptionif the string isnull
- def toByte: Byte
Parse as a
Byte(string must contain only decimal digits and optional leading-or+).Parse as a
Byte(string must contain only decimal digits and optional leading-or+).- Exceptions thrown
java.lang.NumberFormatExceptionIf the string does not contain a parsableByte.
- def toByteOption: Option[Byte]
Try to parse as a
ByteTry to parse as a
Byte- returns
Some(value)if the string contains a valid byte value, otherwiseNone
- Exceptions thrown
java.lang.NullPointerExceptionif the string isnull
- def toDouble: Double
Parse as a
Double(surrounding whitespace is removed with atrim).Parse as a
Double(surrounding whitespace is removed with atrim).- Exceptions thrown
java.lang.NullPointerExceptionIf the string is null.java.lang.NumberFormatExceptionIf the string does not contain a parsableDouble.
- def toDoubleOption: Option[Double]
Try to parse as a
DoubleTry to parse as a
Double- returns
Some(value)if the string is a parsableDouble,Noneotherwise
- Exceptions thrown
java.lang.NullPointerExceptionIf the string is null
- def toFloat: Float
Parse as a
Float(surrounding whitespace is removed with atrim).Parse as a
Float(surrounding whitespace is removed with atrim).- Exceptions thrown
java.lang.NullPointerExceptionIf the string is null.java.lang.NumberFormatExceptionIf the string does not contain a parsableFloat.
- def toFloatOption: Option[Float]
Try to parse as a
FloatTry to parse as a
Float- returns
Some(value)if the string is a parsableFloat,Noneotherwise
- Exceptions thrown
java.lang.NullPointerExceptionIf the string is null
- def toInt: Int
Parse as an
Int(string must contain only decimal digits and optional leading-or+).Parse as an
Int(string must contain only decimal digits and optional leading-or+).- Exceptions thrown
java.lang.NumberFormatExceptionIf the string does not contain a parsableInt.
- def toIntOption: Option[Int]
Try to parse as an
IntTry to parse as an
Int- returns
Some(value)if the string contains a valid Int value, otherwiseNone
- Exceptions thrown
java.lang.NullPointerExceptionif the string isnull
- def toLong: Long
Parse as a
Long(string must contain only decimal digits and optional leading-or+).Parse as a
Long(string must contain only decimal digits and optional leading-or+).- Exceptions thrown
java.lang.NumberFormatExceptionIf the string does not contain a parsableLong.
- def toLongOption: Option[Long]
Try to parse as a
LongTry to parse as a
Long- returns
Some(value)if the string contains a valid long value, otherwiseNone
- Exceptions thrown
java.lang.NullPointerExceptionif the string isnull
- def toShort: Short
Parse as a
Short(string must contain only decimal digits and optional leading-or+).Parse as a
Short(string must contain only decimal digits and optional leading-or+).- Exceptions thrown
java.lang.NumberFormatExceptionIf the string does not contain a parsableShort.
- def toShortOption: Option[Short]
Try to parse as a
ShortTry to parse as a
Short- returns
Some(value)if the string contains a valid short value, otherwiseNone
- Exceptions thrown
java.lang.NullPointerExceptionif the string isnull
- def toString(): String
Returns a string representation of the object.
Returns a string representation of the object.
The default representation is platform dependent.
- returns
a string representation of the object.
- Definition Classes
- Any
- def updated(index: Int, elem: Char): String
A copy of this string with one single replaced element.
A copy of this string with one single replaced element.
- index
the position of the replacement
- elem
the replacing element
- returns
a new string which is a copy of this string with the element at position
indexreplaced byelem.
- Exceptions thrown
IndexOutOfBoundsExceptionifindexdoes not satisfy0 <= index < length.- Note
This method treats a string as a plain sequence of Char code units and makes no attempt to keep surrogate pairs or codepoint sequences together. The user is responsible for making sure such cases are handled correctly. Failing to do so may result in an invalid Unicode string.
- def view: StringView
- Annotations
- @inline()
- def withFilter(p: (Char) => Boolean): StringOps.WithFilter
Creates a non-strict filter of this string.
Creates a non-strict filter of this string.
- p
the predicate used to test elements.
- returns
an object of class
stringOps.WithFilter, which supportsmap,flatMap,foreach, andwithFilteroperations. All these operations apply to those chars of this string which satisfy the predicatep.
- Note
the difference between
c filter pandc withFilter pis that the former creates a new string, whereas the latter only restricts the domain of subsequentmap,flatMap,foreach, andwithFilteroperations.
Deprecated Value Members
- def formatted(fmtstr: String): String
Returns string formatted according to given
formatstring.Returns string formatted according to given
formatstring. Format strings are as forString.format(@see java.lang.String.format).- Implicit
- This member is added by an implicit conversion from StringOps toStringFormat[StringOps] performed by method StringFormat in scala.Predef.
- Definition Classes
- StringFormat
- Annotations
- @deprecated @inline()
- Deprecated
(Since version 2.12.16) Use
formatString.format(value)instead ofvalue.formatted(formatString), or use thef""string interpolator. In Java 15 and later,formattedresolves to the new method in String which has reversed parameters.
- def lines: Iterator[String]
Return all lines in this string in an iterator, excluding trailing line end characters; i.e., apply
.stripLineEndto all lines returned bylinesWithSeparators.Return all lines in this string in an iterator, excluding trailing line end characters; i.e., apply
.stripLineEndto all lines returned bylinesWithSeparators.- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use
linesIterator, because JDK 11 adds alinesmethod on String
- def r(groupNames: String*): Regex
You can follow a string with
.r(g1, ... , gn), turning it into aRegex, with group names g1 through gn.You can follow a string with
.r(g1, ... , gn), turning it into aRegex, with group names g1 through gn."""(\d\d)-(\d\d)-(\d\d\d\d)""".r("month", "day", "year")matches dates and provides its subcomponents through groups named "month", "day" and "year".- groupNames
The names of the groups in the pattern, in the order they appear.
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.7) use inline group names like (?<year>X) instead
- def replaceAllLiterally(literal: String, replacement: String): String
Replace all literal occurrences of
literalwith the literal stringreplacement.Replace all literal occurrences of
literalwith the literal stringreplacement. This method is equivalent to java.lang.String#replace(CharSequence,CharSequence).- literal
the string which should be replaced everywhere it occurs
- replacement
the replacement string
- returns
the resulting string
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.2) Use
s.replaceas an exact replacement
- def →[B](y: B): (StringOps, B)
- Implicit
- This member is added by an implicit conversion from StringOps toArrowAssoc[StringOps] performed by method ArrowAssoc in scala.Predef.
- Definition Classes
- ArrowAssoc
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use
->instead. If you still wish to display it as one character, consider using a font with programming ligatures such as Fira Code.
This is the documentation for the Scala standard library.
Package structure
The scala package contains core types like
Int,Float,ArrayorOptionwhich are accessible in all Scala compilation units without explicit qualification or imports.Notable packages include:
scala.collectionand its sub-packages contain Scala's collections frameworkscala.collection.immutable- Immutable, sequential data-structures such asVector,List,Range,HashMaporHashSetscala.collection.mutable- Mutable, sequential data-structures such asArrayBuffer,StringBuilder,HashMaporHashSetscala.collection.concurrent- Mutable, concurrent data-structures such asTrieMapscala.concurrent- Primitives for concurrent programming such asFuturesandPromisesscala.io- Input and output operationsscala.math- Basic math functions and additional numeric types likeBigIntandBigDecimalscala.sys- Interaction with other processes and the operating systemscala.util.matching- Regular expressionsOther packages exist. See the complete list on the right.
Additional parts of the standard library are shipped as separate libraries. These include:
scala.reflect- Scala's reflection API (scala-reflect.jar)scala.xml- XML parsing, manipulation, and serialization (scala-xml.jar)scala.collection.parallel- Parallel collections (scala-parallel-collections.jar)scala.util.parsing- Parser combinators (scala-parser-combinators.jar)scala.swing- A convenient wrapper around Java's GUI framework called Swing (scala-swing.jar)Automatic imports
Identifiers in the scala package and the
scala.Predefobject are always in scope by default.Some of these identifiers are type aliases provided as shortcuts to commonly used classes. For example,
Listis an alias forscala.collection.immutable.List.Other aliases refer to classes provided by the underlying platform. For example, on the JVM,
Stringis an alias forjava.lang.String.