Home  >  Article  >  Java  >  Example of a method for counting the number of characters and substrings in a string using Java

Example of a method for counting the number of characters and substrings in a string using Java

高洛峰
高洛峰Original
2017-01-18 16:46:402072browse

The example of this article describes the method of counting the number of characters and substrings in a string in Java. Share it with everyone for your reference. The details are as follows:

Here, Java is used to count the number of characters (including numbers, uppercase letters, lowercase letters and other characters) in the string, as well as the number of substrings of the string. number.

The running effect diagram is as follows:

Example of a method for counting the number of characters and substrings in a string using Java

The specific code is as follows:

import java.util.Scanner;
public class Counter {
  static Scanner scanner = new Scanner(System.in);
  public static void count(String s) {
    int low, upper, num, others;
    low = upper = num = others = 0;
    for (int i = 0; i < s.length(); i++) {
      if (Character.isDigit(s.charAt(i))) {
        num++;
        continue;
      }
      if (Character.isLowerCase(s.charAt(i))) {
        low++;
        continue;
      }
      if (Character.isUpperCase(s.charAt(i))) {
        upper++;
        continue;
      } else {
        others++;
      }
    }
    System.out.println(" 大写字母的个数为:" + upper + "\n 小写字母的个数为:" + low+ "\n 数字的个数为: " + num + "\n 其他字符的个数为: " + others);
  }
  public static void subCounter(String str1, String str2) {
    int counter = 0;
    for (int i = 0; i <= str1.length() - str2.length(); i++) {
      if (str1.substring(i, i + str2.length()).equalsIgnoreCase(str2)) {
        counter++;
      }
    }
    System.out.println("子字符串的个数为: " + counter);
  }
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("请输入一个字符串:");
    String string = scanner.nextLine();
    count(string);
    System.out.println("-----------------------------");
    // 查询在这个字符串中存在多少个子字符串str。
    System.out.println("请输入一个您想查询的子字符串:");
    String str = scanner.nextLine();
    subCounter(string, str);
  }
}

I hope this article will be helpful to everyone in java programming.

For more examples of Java methods for counting the number of characters and substrings in a string, please pay attention to the PHP Chinese website for related articles!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn