虽然您可以通过循环来完成此操作,并在每次更改类型时检查增加计数器,但我个人会在此处使用带有正则表达式的 String#replaceAll。
例如:
String str = "215348-jobpoint";
System.out.println("Input: \"" + str + "\"");
// Replace chunks of digits with a single '0':
str = str.replaceAll("\\d+", "0");
System.out.println("After replacing digit chunks: \"" + str + "\"");
// Replace chunks of letters with a single 'A':
str = str.replaceAll("[A-Za-z]+", "A");
System.out.println("After replacing letter chunks: \"" + str + "\"");
// Replace chunks of non-digits and non-letters with a single '~':
str = str.replaceAll("[^A-Za-z\\d]+", "~");
System.out.println("After replacing non-digit/non-letter chunks: \"" + str + "\"");
// Since we transformed every chunk of subsequent characters of the same type to a single character,
// retrieving the length-1 will get our amount of type-changes
int amountOfTypeChunks = str.length();
int amountOfTypeChanges = amountOfTypeChunks -1;
System.out.println("Result (amount of chunks of different types): " + amountOfTypeChunks);
System.out.println("Result (amount of type changes): " + amountOfTypeChanges);
导致:
Input: "215348-jobpoint"
After replacing digit chunks: "0-jobpoint"
After replacing letter chunks: "0-A"
After replacing non-digit/non-letter chunks: "0~A"
Result (amount of chunks of different types): 3
Result (amount of type changes): 2
Try it online.
请注意,您的示例输入 "215348-jobpoint" 有两个类型更改:从 215348 到 -,以及从 - 到 jobpoint,而不是您所说的三个。如果您不管寻找输出3,而是寻找类型块的数量而不是类型更改的数量,您可以在str.length() 之后删除-1(在这种情况下,像@987654334 这样的输入@ 将导致 1 而不是 0)。我已经在上面的代码中添加了两个结果。
另外,我使用的0、A 和~ 可以是任何其他字符。由于我们只想知道替换后得到的字符串的长度,与哪个字符无关(当然不要用字母代替数字)。