带有示例的 Scala String replaceFirst() 方法
replaceFirst()方法与replaceAll相同,但这里只替换所述子字符串的第一次出现。
Method Definition: String replaceFirst(String regex, String replacement)
Return Type: It returns the stated string after replacing the first appearance of stated regular expression with the string we provide.
示例 #1:
// Scala program of replaceFirst()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Applying replaceFirst method
val result = "csoNidhimsoSingh".replaceFirst(".so", "##")
// Displays output
println(result)
}
}
输出:
##NidhimsoSingh
示例 #2:
// Scala program of replaceFirst()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Applying replaceFirst method
val result = "NidhimsoSinghcso".replaceFirst(".so", "*")
// Displays output
println(result)
}
}
输出:
Nidhi*Singhcso
示例#3:
// Scala program of replaceFirst()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Applying replaceFirst method
val result = "fsoNidhimsoSinghcso".replaceFirst(".so", "*")
// Displays output
println(result)
}
}
输出:
*NidhimsoSinghcso