quinta-feira, 3 de junho de 2021

C# - pesquisando ocorrências de caracteres em frase


Já sabemos que podemos usar o método Count()
para contar elementos em listas e arrays,
então logicamente fica fácil enumerar elementos
dentro de uma frase completa mostrando suas ocorrências,
afinal uma string é um array de caracteres.
Neste exemplo estamos usando o método Count()
para retornar o número de elementos em uma sequência
de caracteres, digitada numa entrada de dados
com um textBox do C#.
Desculpem-nos pelas muitas linhas utilizadas
no programa, isto ocorreu porque preferimos
utilizar um Form no lugar do console do Windows.
Veja o vídeo do programa funcionando:





using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Textbox_to_Array {
    public partial class Form1 : Form {
        int a = 0;
        char c;
        string str_1;
        /*============================================================*/
        void Informe ( PaintEventArgs e ) {
            Graphics dc = e.Graphics;
            Font myFont = new System.Drawing.Font ( "Helvetica", 11, FontStyle.Italic );              
            Brush myBrush_1 = new SolidBrush ( System.Drawing.Color.Red );
            Brush myBrush_2 = new SolidBrush ( System.Drawing.Color.Blue );
            Brush myBrush_3 = new SolidBrush ( System.Drawing.Color.Black );
            dc.DrawString ( "Por: ", myFont, myBrush_1, 260, 250 );
            dc.DrawString ( "Samuel Lima ", myFont, myBrush_2, 290, 250 );
            dc.DrawString ( "sa_sp10@hotmail.com ", myFont, myBrush_3, 260, 265 );
        }
        /*============================================================*/
        void Label_1 ( int X, int Y, int W, int H, string st ) {
            label1.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            9.75F, System.Drawing.FontStyle.Italic, 
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            label1.ForeColor = System.Drawing.Color.Blue;
            label1.Location = new System.Drawing.Point ( X, Y );
            label1.Name = "label1";
            label1.Size = new System.Drawing.Size ( W, H );
            label1.TabIndex = 2;
            label1.Text = st;
        }
        /*============================================================*/
        void TextBox_1 ( int X, int Y, int W, int H ) {
            textBox1.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            8F, System.Drawing.FontStyle.Italic, 
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            textBox1.ForeColor = System.Drawing.Color.Black;
            textBox1.Location = new System.Drawing.Point ( X, Y );
            textBox1.Name = "textBox1";
            textBox1.Size = new System.Drawing.Size ( W, H );
            textBox1.TabIndex = 3;
        }
        /*============================================================*/
        void TextBox_2 ( int X, int Y, int W, int H ) {
            textBox2.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            8F, System.Drawing.FontStyle.Italic,
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            textBox2.ForeColor = System.Drawing.Color.Black;
            textBox2.Location = new System.Drawing.Point ( X, Y );
            textBox2.Name = "textBox2";
            textBox2.Size = new System.Drawing.Size ( W, H );
            textBox2.TabIndex = 4;
        }
        /*============================================================*/
        void Label_2 ( int X, int Y, int W, int H, string st ) {
            label2.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            9.75F, System.Drawing.FontStyle.Italic, 
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            label2.ForeColor = System.Drawing.Color.Blue;
            label2.Location = new System.Drawing.Point ( X, Y );
            label2.Name = "label2";
            label2.Size = new System.Drawing.Size ( W, H );
            label2.TabIndex = 5;
            label2.Text = st;
        }
        /*============================================================*/
        void Label_3 ( int X, int Y, int W, int H, string st ) {
            this.label3.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            9.75F, System.Drawing.FontStyle.Italic, 
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            this.label3.ForeColor = System.Drawing.Color.Red;
            this.label3.Location = new System.Drawing.Point ( X, Y );
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size ( W, H );
            label3.TabIndex = 6;
            label3.Text = st;
        }
        /*============================================================*/
        void Label_4 ( int X, int Y, int W, int H, string st ) {
            this.label4.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            9.75F, System.Drawing.FontStyle.Italic,
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            this.label4.ForeColor = System.Drawing.Color.Blue;
            this.label4.Location = new System.Drawing.Point ( X, Y );
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size ( W, H );
            label4.TabIndex = 7;
            label4.Text = st;
        }
        /*============================================================*/
        void Label_5 ( int X, int Y, int W, int H, string st ) {
            this.label5.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            9.75F, System.Drawing.FontStyle.Italic,
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            this.label5.ForeColor = System.Drawing.Color.Red;
            this.label5.Location = new System.Drawing.Point ( X, Y );
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size ( W, H );
            label5.TabIndex = 8;
            label5.Text += st;
        }
        /*============================================================*/
        public void Button_1 ( int X, int Y, int W, int H, string st ) {
            textBox1.Focus ( );
            button1.Location = new Point ( X, Y );
            this.button1.Size = new System.Drawing.Size ( W, H );
            button1.Font = new Font ( "Times New Roman", 10F,
             System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, 0 );
            button1.BackColor = Color.Pink;
            button1.ForeColor = Color.FromArgb ( 0, 0, 0 );
            this.button1.Text = st;
        }
        /*============================================================*/
        public void Button_2 ( int X, int Y, int W, int H, string st ) {
            button2.Location = new Point ( X, Y );
            this.button2.Size = new System.Drawing.Size ( W, H );
            button2.Font = new Font ( "Times New Roman", 13F,
             System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, 0 );
            button2.BackColor = Color.LightGreen;
            button2.ForeColor = Color.FromArgb ( 0, 0, 0 );
            this.button2.Text = st;
        }
        /*============================================================*/
        public void Button_3 ( int X, int Y, int W, int H, string st ) {
            button3.Location = new Point ( X, Y );
            this.button3.Size = new System.Drawing.Size ( W, H );
            button3.Font = new Font ( "Times New Roman", 10F,
            System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, 0 );
            button3.BackColor = Color.Yellow;
            button3.ForeColor = Color.FromArgb ( 0, 0, 0 );
            this.button3.Text = st;
        }
        /*============================================================*/
        public void Button_4 ( int X, int Y, int W, int H, string st ) {
            button4.Location = new Point ( X, Y );
            this.button4.Size = new System.Drawing.Size ( W, H );
            button4.Font = new Font ( "Times New Roman", 10F,
            System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, 0 );
            button4.BackColor = Color.LightCyan;
            button4.ForeColor = Color.FromArgb ( 0, 0, 0 );
            this.button4.Text = st;
        }
        /*============================================================*/
        private void Paint_Imagem ( PaintEventArgs e ) {
            Image newImage = Image.FromFile ( "Moldura_2.bmp" );
            Point ulCorner = new Point ( 0, 0 );
            e.Graphics.DrawImage ( newImage, ulCorner );
        }
        /*============================================================*/
        protected override void OnPaint ( PaintEventArgs e ) {
            Paint_Imagem ( e );
            this.Size = new System.Drawing.Size ( 615, 337 );
            this.Text = "C# - PESQUISANDO OCORRÊNCIAS DE CARACTERES EM FRASE";
            this.BackColor = Color.White;
            Graphics dc = e.Graphics;
            Font myFont = new System.Drawing.Font ( "Consolas", 12,
                FontStyle.Italic );
            Brush myBrush_1 = new SolidBrush ( Color.Red );
            dc.DrawString ( "C# - PESQUISANDO OCORRÊNCIAS DE CARACTERES EM FRASE",
                myFont, myBrush_1, 70, 15 );
            Informe ( e );
        }
        /*============================================================*/
        public Form1 ( ) {
            InitializeComponent ( );
        }
        /*============================================================*/
        private void Button1_Click ( object sender, EventArgs e ) {
            a++;
            //str_1 recebe a frase digitada no textBox1
            str_1 = textBox1.Text;

            if ( a == 1 ) {
                Console.Beep ( );
                label1.Visible = false;
                textBox1.Clear ( );
                textBox1.Visible = false;
                button1.Visible = false;

                Label_2 ( 100, 80, 80, 80, "Frase digitada" );
                Label_3 ( 100, 100, 80, 80, "" + str_1 );
                Label_4 ( 100, 130, 80, 80, "Caractere para pesquisar: " );

                textBox2.Visible = true;
                button3.Visible = true;
                TextBox_2 ( 270, 125, 30, 10 );
                Button_3 ( 320, 125, 35, 22, "Ok" );
                _ = textBox2.Focus ( );
            }
        }
        /*============================================================*/
        private void Form1_Shown ( object sender, EventArgs e ) {
            textBox2.Visible = false;
            button1.Enabled = true;
            button3.Visible = false;
            button4.Visible = false;

            label1.Visible = true;
            Label_1 ( 100, 50, 200, 20, "Digite uma frase: " );
            TextBox_1 ( 210, 45, 130, 10 );
            Button_1 ( 360, 45, 35, 22, "Ok" );
            Button_2 ( 200, 260, 50, 25, "Sair" );
        }
        /*============================================================*/
        private void button3_Click ( object sender, EventArgs e ) {
            //Entra com um caractere no textBox2  
            c = char.Parse ( textBox2.Text );

            //Conta o total de ocorrências do caractere na frase
            int ocorre = str_1.Count ( t => t == c );

            textBox2.Clear ( );
            _ = textBox2.Focus ( );

            Label_5 ( 100, 170, 200, 20, "" );
            label5.Text = "";
            label5.Visible = true;
            label5.Text += "Encontrado ";
            label5.Text += ocorre;
            label5.Text += " ocorrênciasc de ";
            label5.Text += c;

            button4.Visible = true;
            Button_4 ( 200, 220, 120, 25, "Nova operação" );         
        }
        /*============================================================*/
        private void button4_Click ( object sender, EventArgs e ) {
            button3.Visible = false;
            button4.Visible = false;
            textBox2.Visible = false;

            textBox1.Visible = true;
            button1.Visible = true;

            label2.Text = "";
            label3.Text = "";
            label4.Text = "";
            label5.Text = "";

            label1.Visible = true;
            Label_1 ( 100, 50, 200, 20, "Digite uma frase: " );

            a = 0;
            c = ' ';
            str_1 = " ";
            textBox1.Clear ( );
            _ = textBox1.Focus ( );
            textBox2.Clear ( );
        }
        /*============================================================*/
        private void button2_Click ( object sender, EventArgs e ) {
            Application.Exit ( );
        }
        /*============================================================*/
    }
}

quarta-feira, 2 de junho de 2021

C# - pesquisando ocorrências em array de inteiros


Quando precisamos contar elementos em listas ou arrays,
podemos usar o método Count();
Este método é perfeito para fazer enumerações,
Então se informarmos um elemento para pesquisa,
em um array que é o nosso caso ele retorna o número
da contagem do elemento informado dentro do array.
Em um outro exemplo seria muito fácil usar o método Count()
para informar a quantidade de elementos maior ou menor
que um outro previamente informado.
isto impressiona porque quando fizemos isto em C,
além das várias linhas necessárias que utilizamos,
a complexidade foi um fato.
Se tivesse feito isto para imprimir os resultados
no console do windows, acho que pouco mais de trinta
linhas já seriam suficientes, mas como queria
relembrar um pouco do que já fizemos em C#,
programando num Form, o código ficou bem extenso.
Se interessou pelo código, basta clicar no link abaixo,
mas antes assista o vídeo do programa funcionando.




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Textbox_to_Array {
    public partial class Form1 : Form {
        int a = 0;
        int num;
        readonly int [ ] arr = new int [ 11 ];
        string str_1;
        /*============================================================*/
        void Informe ( PaintEventArgs e ) {
            Graphics dc = e.Graphics;
            Font myFont = new System.Drawing.Font ( "Helvetica", 11,
                FontStyle.Italic );
            Brush myBrush_1 = new SolidBrush ( System.Drawing.Color.Red );
            Brush myBrush_2 = new SolidBrush ( System.Drawing.Color.Blue );
            Brush myBrush_3 = new SolidBrush ( System.Drawing.Color.Black );
            dc.DrawString ( "Por: ", myFont, myBrush_1, 260, 250 );
            dc.DrawString ( "Samuel Lima ", myFont, myBrush_2, 290, 250 );
            dc.DrawString ( "sa_sp10@hotmail.com ", myFont, myBrush_3, 260, 265 );
        }
        /*============================================================*/
        void Label_1 ( int X, int Y, int W, int H, string st ) {
            //this.label1.AutoSize = true;
            label1.Font = new System.Drawing.Font ( "Microsoft Sans Serif", 9.75F,
            System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            label1.ForeColor = System.Drawing.Color.Blue;
            label1.Location = new System.Drawing.Point ( X, Y );
            label1.Name = "label1";
            label1.Size = new System.Drawing.Size ( W, H );
            label1.TabIndex = 2;
            label1.Text = st;
        }
        /*============================================================*/
        void TextBox_1 ( int X, int Y, int W, int H ) {
            //this.label1.AutoSize = true;
            textBox1.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            8F, System.Drawing.FontStyle.Italic, 
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            textBox1.ForeColor = System.Drawing.Color.Blue;
            textBox1.Location = new System.Drawing.Point ( X, Y );
            textBox1.Name = "textBox1";
            textBox1.Size = new System.Drawing.Size ( W, H );
            textBox1.TabIndex = 3;
        }
        /*============================================================*/
        void TextBox_2 ( int X, int Y, int W, int H ) {
            //this.label1.AutoSize = true;
            textBox2.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            8F, System.Drawing.FontStyle.Italic,
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            textBox2.ForeColor = System.Drawing.Color.Blue;
            textBox2.Location = new System.Drawing.Point ( X, Y );
            textBox2.Name = "textBox2";
            textBox2.Size = new System.Drawing.Size ( W, H );
            textBox2.TabIndex = 4;
        }
        /*============================================================*/
        void Label_2 ( int X, int Y, int W, int H, string st ) {
            //this.label1.AutoSize = true;
            label2.Font = new System.Drawing.Font ( "Microsoft Sans Serif", 9.75F,
            System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            label2.ForeColor = System.Drawing.Color.Blue;
            label2.Location = new System.Drawing.Point ( X, Y );
            label2.Name = "label2";
            label2.Size = new System.Drawing.Size ( W, H );
            label2.TabIndex = 5;
            label2.Text = st;
        }
        /*============================================================*/
        void Label_3 ( int X, int Y, int W, int H, string st ) {
            //this.label1.AutoSize = true;
            this.label3.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            9.75F, System.Drawing.FontStyle.Italic, 
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            this.label3.ForeColor = System.Drawing.Color.Red;
            this.label3.Location = new System.Drawing.Point ( X, Y );
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size ( W, H );
            label3.TabIndex = 6;
            label3.Text = st;
        }
        /*============================================================*/
        void Label_4 ( int X, int Y, int W, int H, string st ) {
            //this.label1.AutoSize = true;
            this.label4.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            9.75F, System.Drawing.FontStyle.Italic,
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            this.label4.ForeColor = System.Drawing.Color.Blue;
            this.label4.Location = new System.Drawing.Point ( X, Y );
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size ( W, H );
            label4.TabIndex = 7;
            label4.Text = st;
        }
        /*============================================================*/
        void Label_5 ( int X, int Y, int W, int H, string st ) {
            //this.label1.AutoSize = true;
            this.label5.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            9.75F, System.Drawing.FontStyle.Italic,
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            this.label5.ForeColor = System.Drawing.Color.Red;
            this.label5.Location = new System.Drawing.Point ( X, Y );
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size ( W, H );
            label5.TabIndex = 8;
            label5.Text += st;
        }
        /*============================================================*/
        public void Button_1 ( int X, int Y, int W, int H, string st ) {
            textBox1.Focus ( );
            button1.Location = new Point ( X, Y );
            this.button1.Size = new System.Drawing.Size ( W, H );
            button1.Font = new Font ( "Times New Roman", 10F,
             System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, 0 );
            button1.BackColor = Color.Pink;
            button1.ForeColor = Color.FromArgb ( 0, 0, 0 );
            this.button1.Text = st;
        }
        /*============================================================*/
        public void Button_2 ( int X, int Y, int W, int H, string st ) {
            button2.Location = new Point ( X, Y );
            this.button2.Size = new System.Drawing.Size ( W, H );
            button2.Font = new Font ( "Times New Roman", 13F,
             System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, 0 );
            button2.BackColor = Color.LightGreen;
            button2.ForeColor = Color.FromArgb ( 0, 0, 0 );
            this.button2.Text = st;
        }
        /*============================================================*/
        public void Button_3 ( int X, int Y, int W, int H, string st ) {
            button3.Location = new Point ( X, Y );
            this.button3.Size = new System.Drawing.Size ( W, H );
            button3.Font = new Font ( "Times New Roman", 10F,
            System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, 0 );
            button3.BackColor = Color.Yellow;
            button3.ForeColor = Color.FromArgb ( 0, 0, 0 );
            this.button3.Text = st;
        }
        /*============================================================*/
        public void Button_4 ( int X, int Y, int W, int H, string st ) {
            button4.Location = new Point ( X, Y );
            this.button4.Size = new System.Drawing.Size ( W, H );
            button4.Font = new Font ( "Times New Roman", 10F,
            System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, 0 );
            button4.BackColor = Color.LightCyan;
            button4.ForeColor = Color.FromArgb ( 0, 0, 0 );
            this.button4.Text = st;
        }
        /*============================================================*/
        private void Paint_Imagem ( PaintEventArgs e ) {
            Image newImage = Image.FromFile ( "Moldura_1.bmp" );
            Point ulCorner = new Point ( 0, 0 );
            e.Graphics.DrawImage ( newImage, ulCorner );
        }
        /*============================================================*/
        protected override void OnPaint ( PaintEventArgs e ) {
            Paint_Imagem ( e );
            this.Size = new System.Drawing.Size ( 615, 337 );
            this.Text = "C# - PESQUISANDO OCORRÊNCIAS EM ARRAY DE INTEIROS";
            this.BackColor = Color.White;
            Graphics dc = e.Graphics;
            Font myFont = new System.Drawing.Font ( "Consolas", 12,
                FontStyle.Italic );
            Brush myBrush_1 = new SolidBrush ( Color.Red );
            dc.DrawString ( "C# - PESQUISANDO OCORRÊNCIAS EM ARRAY DE INTEIROS1",
                myFont, myBrush_1, 70, 15 );
            Informe ( e );
        }
        /*============================================================*/
        public Form1 ( ) {
            InitializeComponent ( );
        }
        /*============================================================*/
        private void Button1_Click ( object sender, EventArgs e ) {
            int i;
            arr [ a ] = Int32.Parse ( textBox1.Text );
            _ = textBox1.Focus ( );
            //limpa o campo do TextBox a cada novo click do botão
            textBox1.Clear ( );
            if ( textBox1.Text == " " ) {
                Console.Beep ( );
            }
                //Quando a recebe o quinto clique imprime.
                if ( a == 10 ) {
                    Console.Beep ( );
                    Label_2 ( 200, 80, 80, 80, "Números digitados" );
                    for ( i = 0; i < arr.Length; i++ ) {
                        str_1 += ( arr [ i ] + " " );
                    }
                    Label_3 ( 200, 100, 80, 80, "" + str_1 );

                    Label_4 ( 200, 130, 80, 80, "Número para pesquisar" );
                    textBox2.Visible = true;
                    button3.Visible = true;
                    TextBox_2 ( 360, 130, 30, 10 );
                    Button_3 ( 400, 130, 35, 22, "Ok" );

                label1.Text = "";
                textBox1.Visible = false;
                button1.Visible = false;
            }
            //A variável inteira a indexa o array a cada click no botão
            a++;
        }
        /*============================================================*/
        private void Form1_Shown ( object sender, EventArgs e ) {
            textBox2.Visible = false;
            button1.Enabled = true;
            button3.Visible = false;
            button4.Visible = false;

            label1.Visible = true;
            Label_1 ( 200, 50, 200, 20, "Digite um número" );
            TextBox_1 ( 320, 50, 30, 10 );
            Button_1 ( 360, 50, 35, 22, "Ok" );
            Button_2 ( 200, 260, 50, 25, "Sair" );
        }
        /*============================================================*/
        private void button3_Click ( object sender, EventArgs e ) {
            num = Int32.Parse ( textBox2.Text );
            int ocorre = arr.Count ( t => t == num );

            textBox2.Clear ( );
            _ = textBox2.Focus ( );

            Label_5 ( 200, 170, 200, 20, "" );
            label5.Text = "";
            label5.Visible = true;
            label5.Text += "Encontrado ";
            label5.Text += ocorre;
            label5.Text += " ocorrênciasc de ";
            label5.Text += num;

            button4.Visible = true;
            Button_4 ( 200, 220, 120, 25, "Nova operação" );         
        }
        /*============================================================*/
        private void button4_Click ( object sender, EventArgs e ) {
            button3.Visible = false;
            button4.Visible = false;
            textBox2.Visible = false;

            textBox1.Visible = true;
            button1.Visible = true;

            label2.Text = "";
            label3.Text = "";
            label4.Text = "";
            label5.Text = "";
            
            Label_1 ( 200, 50, 200, 20, "Digite um número" );

            a = 0;
            num = 0;
            str_1 = " ";
            textBox1.Clear ( );
            _ = textBox1.Focus ( );
            textBox2.Clear ( );
        }
        /*============================================================*/
        private void button2_Click ( object sender, EventArgs e ) {
            Application.Exit ( );
        }
        /*============================================================*/
    }
}