计算字符串中的特定字符(Java)

时间:2021-02-04 14:56:56

I have a homework assignment to count specific chars in string.

我有一个家庭作业来计算字符串中的特定字符。

For example: string = "America"

例如:string = "America"

The output should be = a appear 2 times, m appear 1 time, e appear 1 time, r appear 1 time, i appear 1 time and c appear 1 time

输出应该是= a出现2次,m出现1次,e出现1次,r出现1次,我出现1次,c出现1次

public class switchbobo {

/**
 * @param args
 */     // TODO Auto-generated method stub
  public static void main(String[] args){
    String s = "BUNANA";
    String lower = s.toLowerCase();
    char[] c = lower.toCharArray(); // converting to a char array
    int freq =0, freq2 = 0,freq3 = 0,freq4=0,freq5 = 0;

    for(int i = 0; i< c.length;i++) {
        if(c[i]=='a') // looking for 'a' only
          freq++;
        if(c[i]=='b')
          freq2++;
        if (c[i]=='c') {
          freq3++;
        }

        if (c[i]=='d') {
          freq4++;
        }       
    }
    System.out.println("Total chars "+c.length);
    if (freq > 0) {
      System.out.println("Number of 'a' are "+freq);
    }
  }
}

code above is what I have done, but I think it is not make sense to have 26 variables (one for each letter). Do you guys have alternative result?

上面的代码是我所做的,但是我认为有26个变量(每个字母一个)是没有意义的。你们有别的选择吗?

8 个解决方案

#1


7  

Obviously your intuition of having a variable for each letter is correct.

显然你对每个字母都有一个变量的直觉是正确的。

The problem is that you don't have any automated way to do the same work on different variables, you don't have any trivial syntax which helps you doing the same work (counting a single char frequency) for 26 different variables.

问题是,您没有任何自动化的方法来在不同的变量上执行相同的工作,您没有任何琐碎的语法,可以帮助您完成26个不同变量的相同工作(计算单个字符的频率)。

So what could you do? I'll hint you toward two solutions:

那么你能做什么呢?我将提示你两个解决方案:

  • you can use an array (but you will have to find a way to map character a-z to indices 0-25, which is somehow trivial is you reason about ASCII encoding)
  • 您可以使用数组(但是您必须找到一种方法将字符a-z映射到索引0-25,这在某种程度上是微不足道的,因为您需要解释ASCII编码)
  • you can use a HashMap<Character, Integer> which is an associative container that, in this situation, allows you to have numbers mapped to specific characters so it perfectly fits your needs
  • 您可以使用HashMap ,它是一个关联容器,在这种情况下,允许您将数字映射到特定的字符,这样它就非常适合您的需要 ,>

#2


4  

You can use HashMap of Character key and Integer value.

可以使用字符键和整型值的HashMap。

HashMap<Character,Integer> 

iterate through the string

遍历字符串

-if the character exists in the map get the Integer value and increment it.
-if not then insert it to map and set the integer value for 0

This is a pseudo code and you have to try coding it

这是一个伪代码,您必须尝试编写它。

#3


2  

I am using a HashMap for the solution.

我正在使用HashMap作为解决方案。

import java.util.*;

public class Sample2 {

/**
 * @param args
 */
public static void main(String[] args) 
 {
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    String test = "BUNANA";
    char[] chars = test.toCharArray();

    for(int i=0; i<chars.length;i++)
    {
        if(!map.containsKey(chars[i]))
        {
            map.put(chars[i], 1);
        }
        map.put(chars[i], map.get(chars[i])+1);
    }

    System.out.println(map.toString());
 }

}

Produced Output - {U=2, A=3, B=2, N=3}

输出- {U=2, A=3, B=2, N=3}

#4


0  

In continuation to Jack's answer the following code could be your solution. It uses the an array to store the frequency of characters.

继续杰克的回答,下面的代码可以作为您的解决方案。它使用一个数组来存储字符的频率。

public class SwitchBobo 
{
   public static void main(String[] args)
   {
      String s = "BUNANA";
      String lower = s.toLowerCase();
      char[] c = lower.toCharArray();
      int[] freq = new int[26];
      for(int i = 0; i< c.length;i++) 
      {
         if(c[i] <= 122)
         {
            if(c[i] >= 97)
            {
               freq[(c[i]-97)]++;
            }
         }        
      }
      System.out.println("Total chars " + c.length);
      for(int i = 0; i < 26; i++)
      {
         if(freq[i] != 0)   
            System.out.println(((char)(i+97)) + "\t" + freq[i]);
      }      
   }
}

It will give the following output:

输出如下:

Total chars 6
a       2
b       1
n       2
u       1

#5


0  

int a[]=new int[26];//default with count as 0
for each chars at string
if (String having uppercase)
  a[chars-'A' ]++
if lowercase 
then a[chars-'a']++

#6


0  

public class TestCharCount {
    public static void main(String args[]) {
        String s = "america";
        int len = s.length();
        char[] c = s.toCharArray();
        int ct = 0;
        for (int i = 0; i < len; i++) {
            ct = 1;
            for (int j = i + 1; j < len; j++) {
                if (c[i] == ' ')
                    break;
                if (c[i] == c[j]) {
                    ct++;
                    c[j] = ' ';
                }

            }
            if (c[i] != ' ')
                System.out.println("number of occurance(s) of " + c[i] + ":"
                        + ct);

        }
    }
}

#7


0  

maybe you can use this

也许你可以用这个。

public static int CountInstanceOfChar(String text, char character   ) {
    char[] listOfChars = text.toCharArray();
    int total = 0 ;
    for(int charIndex = 0 ; charIndex < listOfChars.length ; charIndex++)
        if(listOfChars[charIndex] == character)
            total++;
    return total;
}

for example:

例如:

String text = "america";
char charToFind = 'a';
System.out.println(charToFind +" appear " + CountInstanceOfChar(text,charToFind) +" times");

#8


0  

Count char 'l' in the string.

数字符串中的char 'l'。

  String test = "Hello";
  int count=0;
  for(int i=0;i<test.length();i++){
   if(test.charAt(i)== 'l'){
       count++;
        }
    }

or

int count=  StringUtils.countMatches("Hello", "l");

#1


7  

Obviously your intuition of having a variable for each letter is correct.

显然你对每个字母都有一个变量的直觉是正确的。

The problem is that you don't have any automated way to do the same work on different variables, you don't have any trivial syntax which helps you doing the same work (counting a single char frequency) for 26 different variables.

问题是,您没有任何自动化的方法来在不同的变量上执行相同的工作,您没有任何琐碎的语法,可以帮助您完成26个不同变量的相同工作(计算单个字符的频率)。

So what could you do? I'll hint you toward two solutions:

那么你能做什么呢?我将提示你两个解决方案:

  • you can use an array (but you will have to find a way to map character a-z to indices 0-25, which is somehow trivial is you reason about ASCII encoding)
  • 您可以使用数组(但是您必须找到一种方法将字符a-z映射到索引0-25,这在某种程度上是微不足道的,因为您需要解释ASCII编码)
  • you can use a HashMap<Character, Integer> which is an associative container that, in this situation, allows you to have numbers mapped to specific characters so it perfectly fits your needs
  • 您可以使用HashMap ,它是一个关联容器,在这种情况下,允许您将数字映射到特定的字符,这样它就非常适合您的需要 ,>

#2


4  

You can use HashMap of Character key and Integer value.

可以使用字符键和整型值的HashMap。

HashMap<Character,Integer> 

iterate through the string

遍历字符串

-if the character exists in the map get the Integer value and increment it.
-if not then insert it to map and set the integer value for 0

This is a pseudo code and you have to try coding it

这是一个伪代码,您必须尝试编写它。

#3


2  

I am using a HashMap for the solution.

我正在使用HashMap作为解决方案。

import java.util.*;

public class Sample2 {

/**
 * @param args
 */
public static void main(String[] args) 
 {
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    String test = "BUNANA";
    char[] chars = test.toCharArray();

    for(int i=0; i<chars.length;i++)
    {
        if(!map.containsKey(chars[i]))
        {
            map.put(chars[i], 1);
        }
        map.put(chars[i], map.get(chars[i])+1);
    }

    System.out.println(map.toString());
 }

}

Produced Output - {U=2, A=3, B=2, N=3}

输出- {U=2, A=3, B=2, N=3}

#4


0  

In continuation to Jack's answer the following code could be your solution. It uses the an array to store the frequency of characters.

继续杰克的回答,下面的代码可以作为您的解决方案。它使用一个数组来存储字符的频率。

public class SwitchBobo 
{
   public static void main(String[] args)
   {
      String s = "BUNANA";
      String lower = s.toLowerCase();
      char[] c = lower.toCharArray();
      int[] freq = new int[26];
      for(int i = 0; i< c.length;i++) 
      {
         if(c[i] <= 122)
         {
            if(c[i] >= 97)
            {
               freq[(c[i]-97)]++;
            }
         }        
      }
      System.out.println("Total chars " + c.length);
      for(int i = 0; i < 26; i++)
      {
         if(freq[i] != 0)   
            System.out.println(((char)(i+97)) + "\t" + freq[i]);
      }      
   }
}

It will give the following output:

输出如下:

Total chars 6
a       2
b       1
n       2
u       1

#5


0  

int a[]=new int[26];//default with count as 0
for each chars at string
if (String having uppercase)
  a[chars-'A' ]++
if lowercase 
then a[chars-'a']++

#6


0  

public class TestCharCount {
    public static void main(String args[]) {
        String s = "america";
        int len = s.length();
        char[] c = s.toCharArray();
        int ct = 0;
        for (int i = 0; i < len; i++) {
            ct = 1;
            for (int j = i + 1; j < len; j++) {
                if (c[i] == ' ')
                    break;
                if (c[i] == c[j]) {
                    ct++;
                    c[j] = ' ';
                }

            }
            if (c[i] != ' ')
                System.out.println("number of occurance(s) of " + c[i] + ":"
                        + ct);

        }
    }
}

#7


0  

maybe you can use this

也许你可以用这个。

public static int CountInstanceOfChar(String text, char character   ) {
    char[] listOfChars = text.toCharArray();
    int total = 0 ;
    for(int charIndex = 0 ; charIndex < listOfChars.length ; charIndex++)
        if(listOfChars[charIndex] == character)
            total++;
    return total;
}

for example:

例如:

String text = "america";
char charToFind = 'a';
System.out.println(charToFind +" appear " + CountInstanceOfChar(text,charToFind) +" times");

#8


0  

Count char 'l' in the string.

数字符串中的char 'l'。

  String test = "Hello";
  int count=0;
  for(int i=0;i<test.length();i++){
   if(test.charAt(i)== 'l'){
       count++;
        }
    }

or

int count=  StringUtils.countMatches("Hello", "l");