将字符移动到scala中的字符串末尾



我有一个文件,其中包含以下类型的字符串:

1 2 a 3 4
5 b 6 c 7

我想把所有的字母移到字符串的末尾,所以输出将是:

1 2 3 4 a
5 6 7 b c

我试过这种方法:

line.replaceAll("\D+", "") + line.replaceAll("\d+", "")

但它给出的输出为:

1234    a
567   b c

我想保留空白,并在任意行数的末尾获得所有字母的输出。

PS:我正在为spark-scala编写代码,所以请向我展示scala方法

假设您有file.txt,内容如下:

1 2 a 3 4
5 b 6 c 7
10 b c 11 12

您可以使用mapsplittoListsortedmkString来实现您想要的结果:

import java.io.File
import java.io.PrintWriter
import scala.io.Source
object Main {
def main(args: Array[String]): Unit = {
val f = new File("file.txt")
val temp = new File("file.tmp")
val w = new PrintWriter(temp)
Source
.fromFile(f)
.getLines
.map { x =>
x
.split(' ')
.toList
.sorted
.mkString(" ")
}
.foreach(x => w.println(x))
w.close()
temp.renameTo(f)
}
}

运行以上file.txt

1 2 3 4 a
5 6 7 b c
10 11 12 b c

您可以利用字符在ASCII表中按顺序排序的优势。

def sortStringWithSpaces(str: String): String =
str.split(' ').sorted.mkString(" ")

你可以这样使用:

sortStringWithSpaces("1 2 a 3 4")
// res: String = "1 2 3 4 a"
sortStringWithSpaces("5 b 6 c 7")
// res: String = "5 6 7 b c"
sortStringWithSpaces("10 b c 11 12")
// res: String = "10 11 12 b c"

您可以在此处看到运行的代码。

当前方法的主要问题是,第二个替换还需要删除空白,否则它只会删除数字,但会留下字母和空格。然后,您需要一个额外的步骤来重新引入每个角色之间的原始空间。假设您想使用Java风格的方法,您可以尝试:

// Java version.
String line = "5 b 6 c 7";
String output = line.replaceAll("\D+", "") +
line.replaceAll("[\d\s]+", "");
output = output.replaceAll("(?=.)", " ");
System.out.println(output);
// Scala version.
val line = "5 b 6 c 7"
var output = line.replaceAll("\D+", "") +
line.replaceAll("[\d\s]+", "")
output = output.replaceAll("(?=.)", " ")
println(output)

两种打印:

5 6 7 b c

我知道我有点迟到了,但你可以做的另一件事是:

def sortStringWhitspaces(str: String): String = {
val partitioned = str.split(' ').partition(x => Try(x.toInt).isSuccess)
(partitioned._1 ++ partitioned._2).mkString(" ")
}

这种方法的优点是不需要对数字和字母进行排序。首先,您没有在问题中指定是否需要保留原始顺序,但排序并不能做到这一点。第二件事,排序可能会占用效率,而这个解决方案是O(n)

代码在Scastie运行。

最新更新