8

文字列内の特定の文字を数える宿題があります。

例えば:string = "America"

出力は次のようになります =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

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);
    }
  }
}

上記のコードは私が行ったものですが、26 個の変数 (文字ごとに 1 つ) を持つことは意味がないと思います。代わりの結果はありますか?

4

8 に答える 8

7

明らかに、文字ごとに変数を持つというあなたの直感は正しいです。

問題は、異なる変数に対して同じ作業を行う自動化された方法がないことです。26 の異なる変数に対して同じ作業 (単一の文字頻度をカウントする) を行うのに役立つ単純な構文はありません。

それで、あなたは何ができますか?2 つの解決策を示します。

  • 配列を使用できます(ただし、文字a-zを indexにマップする方法を見つける必要があります0-25。これは、ASCIIエンコーディングについて理由があるため、何とか簡単です)
  • HashMap<Character, Integer>この状況では、ニーズに完全に適合するように、特定の文字に数字をマップできる連想コンテナである を使用できます。
于 2012-06-03T00:25:18.643 に答える
4

HashMap文字キーと整数値を使用できます。

HashMap<Character,Integer> 

文字列を反復処理する

-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

これは疑似コードであり、コーディングしてみる必要があります

于 2012-06-03T00:25:31.697 に答える
2

ソリューションに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());
 }

}

生成された出力-{U=2、A = 3、B = 2、N = 3}

于 2012-11-09T20:47:31.917 に答える
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']++
于 2013-03-28T15:43:37.210 に答える
0

多分あなたはこれを使うことができます

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;
}

例えば:

String text = "america";
char charToFind = 'a';
System.out.println(charToFind +" appear " + CountInstanceOfChar(text,charToFind) +" times");
于 2014-02-19T06:02:54.487 に答える
0

ジャックの答えに続いて、次のコードが解決策になる可能性があります。配列を使用して、文字の頻度を格納します。

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]);
      }      
   }
}

次の出力が得られます。

Total chars 6
a       2
b       1
n       2
u       1
于 2012-06-03T05:27:54.543 に答える
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);

        }
    }
}
于 2013-04-26T20:12:22.507 に答える