字符串中的Java字符 [英] java characters in a string

查看:89
本文介绍了字符串中的Java字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的问题是我需要让用户输入字符串。然后他们将输入要计算的字符。因此,该程序应该<< c $ c>计算输入的字符出现在字符串中的次数,这是我的问题。如果有人可以给我一些有关如何执行此操作的信息,将不胜感激。

so my problem is that I need to get the user to enter a string. then they will enter a character that they want counted. So the program is supposed to count how many times the character they entered will appear in the string, this is my issue. If someone can give me some information as to how to do this, it'll be greatly appreciated.

import java.util.Scanner;
public class LetterCounter {

public static void main(String[] args) {
    Scanner keyboard= new Scanner(System.in);

    System.out.println("please enter a word");//get the word from the user
    String word= keyboard.nextLine();
    System.out.println("Enter a character");//Ask the user to enter the character they wan counted in the string
    String character= keyboard.nextLine();

}

}


推荐答案

这应该可以做到。它的作用是获取字符串,查找字符,遍历字符串以查找匹配项,计算匹配项的数量,然后返回信息。有更优雅的方法(例如,使用正则表达式匹配器也可以)。

This should do it. What it does is that it gets a string to look at, gets a character to look at, iterates through the string looking for matches, counts the number of matches, and then returns the information. There are more elegant ways to do this (for example, using a regex matcher would also work).

@SuppressWarnings("resource") Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string:\t");
String word = scanner.nextLine();

System.out.print("Enter a character:\t");
String character = scanner.nextLine();

char charVar = 0;
if (character.length() > 1) {
    System.err.println("Please input only one character.");
} else {
    charVar = character.charAt(0);
}

int count = 0;
for (char x : word.toCharArray()) {
    if (x == charVar) {
        count++;
    }
}

System.out.println("Character " + charVar + " appears " + count + (count == 1 ? " time" : " times"));

这篇关于字符串中的Java字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆