1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

2つの文字列を比較し、足りない文字数を数える

Last updated at Posted at 2016-06-19

<注意点・備考>

  • 備忘録として記載。
  • コード参考、流用時は自己責任でお願いします。

【要件】

2つの文字列(TRUE文字列、FALSE文字列)を比較し、
TRUE文字列内に含まれる文字が、FALSE文字列内では何個不足しているかを数える。

例1.
TRUE文字列 = "abcdef"
FALSE文字列 = "abcdeg"
不足文字数:1つ('f'が1つ足りない)
例2.
TRUE文字列 = "abcdff"
FALSE文字列 = "abcfef"
不足文字数:2つ('d'と'f'が1つずつ足りない)
例3.
TRUE文字列 = "abcdef"
FALSE文字列 = "abc"
不足文字数:0つ('d'と'e'と'f'が1つずつ足りない)
例4.
TRUE文字列 = "abc"
FALSE文字列 = "abcdef"
不足文字数:0つ(TRUE文字列内の文字はFALSE文字列内にすべて含まれている)

入出力

コマンドライン上で入出力を行う。

 入力

TRUE文字列
FALSE文字列

 出力

足りない文字数

設計

1.TRUR文字列内の文字と、その文字が出現する回数を管理するDictionary(以下、TRUE文字列用辞書と呼称)を作成
2.TRUE文字列の文字列の先頭から1文字ずつ取り出し、
 TRUE文字列用辞書に取り出した文字列が格納済みでないかチェックする。
3.格納されていなかったら、取り出した文字が、TRUE文字列の文字列内に何回出現するか確認する。
4,取り出した文字と出現回数を検索セット2次元配列に格納する。
5.TRUE文字列用辞書の1番目から、文字とその出現回数を取り出す。
6.取り出した文字列の、FALSE文字列での出現回数をチェックする。
7.取り出した文字列の、TRUE文字列での出現回数 - FALSE文字列での出現回数を行う。
8.7.の値が0より大きければ、足りない文字の個数に加算していく。

ソースコード

using System;
using System.Collections.Generic;
using System.Linq;

    class Program
    {
        static void Main(string[] args)
        {
            //FALSE文字列
            string falseString = System.Console.ReadLine();
            //TRUE文字列
            string trueString = System.Console.ReadLine();

            Dictionary<char, int> serchSet = new Dictionary<char, int>();
            int diffCount = 0 ;

            foreach(char c in trueString )
            {
                int cCountTrue = 0;
                if(!serchSet.Keys.Contains(c))
                {
           //文字列中における特定文字の出現回数をカウント
                    cCountTrue= trueString .Length - trueString .Replace(c.ToString(),"").Length;
                    serchSet.Add(c, cCountTrue);
                }

            }

            //Dictionaryの取り出し
            foreach(KeyValuePair<char, int>pair in serchSet)
            {
                int cCountFalse = 0;
                int diff = 0;
                cCountFalse= falseString .Length - falseString .Replace(pair.Key.ToString(), "").Length;
                diff = pair.Value - cCountFalse;
                if(diff >0 )
                {
                    diffCount += diff;
                }

            }
            Console.WriteLine(diffCount);
       }
    }

参考ページ

・文字列中における特定文字の出現回数をカウント
http://www.atmarkit.co.jp/fdotnet/dotnettips/911countchar/countchar.html

1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?