繁体   English   中英

Java计算字符串中数字,特殊字符和字母的更改次数

[英]Java count the number of changes in Digits, special characters and letters in a string

我想计算数字,字符串中特殊字符和字母的更改次数,例如:

`215348-jobpoint` 

包含3个从“ 8”到特殊字符“-”到字母“ j”的变化。 因此,基本上,我尝试遍历char数组,并检查该数组中的实际和下一个char,如果实际和下一个char属于同一Type实例。 EG,如果它们具有相同类型的字母(字母)或相同的实例号,或相同类型的特殊字符...我该怎么做?

希望这可以帮助使用大小为3的String数组。将所有特殊字符保留在一个位置,将所有数字保留在一个位置,将字母保留在一个位置,例如arr = {“ 01 ... 9”,“!.... @”,“ a。 ... z“}现在检查每个字符是否包含在arr中的不同位置,然后增加计数。 您可以保存前一个字符的位置。

if(!arr[previousKey].contains(character))
{
    count++;
    change previousKey to position which contain the character
}
else
    continue;

尽管您可以使用循环来完成此操作,并在每次更改类型时检查一次,然后增加一个计数器,但我个人还是在这里使用带有regex的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

在线尝试。

请注意,示例输入"215348-jobpoint"具有两种类型更改:从215348-和从-jobpoint ,而不是您所说的三个。 如果您不确定要查找输出3 ,而是要查找类型块的数量而不是类型更改的数量,则可以在str.length()之后删除-1 (在这种情况下,输入为"abc"将导致1而不是0 )。 我已经在上面的代码中添加了两个结果。

另外,我使用的0A~可以是任何其他字符。 因为我们只想知道替换后结果String的长度,所以它与哪个字符无关(尽管当然不要用字母代替数字)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM