【问题标题】:Java count the number of changes in Digits, special characters and letters in a stringJava计算字符串中数字、特殊字符和字母的变化次数
【发布时间】:2019-10-08 20:52:12
【问题描述】:

我想统计一个字符串中数字和特殊字符和字母的变化次数,例如:

`215348-jobpoint` 

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

【问题讨论】:

标签: java string count


【解决方案1】:

希望这会有所帮助 取大小为三的字符串数组。将所有特殊字符放在一个位置,所有数字放在一个位置,字母放在一个位置 比如 arr = {"01...9","!....@","a....z"} 现在检查每个字符是否包含在 arr 中的不同位置,然后增加计数。 可以保存前一个字符的位置。

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

【讨论】:

    【解决方案2】:

    虽然您可以通过循环来完成此操作,并在每次更改类型时检查增加计数器,但我个人会在此处使用带有正则表达式的 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 和~ 可以是任何其他字符。由于我们只想知道替换后得到的字符串的长度,与哪个字符无关(当然不要用字母代替数字)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多