terça-feira, 22 de junho de 2021

C# - Jagged array de strings ( arrays irregulares )

 Postando exemplos práticos:


//Inicializando array jagged bidimensional de strings
using System;
using System.Collections;

class Arr {
    /*============================================================*/
    void Informe ( ) {
        Console.BackgroundColor = ConsoleColor.White;
        Console.SetCursorPosition ( 20, 16 );
        Console.ForegroundColor = ConsoleColor.Red;
        Console.Write ( "Por: " );
        Console.SetCursorPosition ( 25, 16 );
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.Write ( "Samuel Lima" );
        Console.SetCursorPosition ( 20, 17 );
        Console.ForegroundColor = ConsoleColor.Black;
        Console.Write ( "sa_sp10@hotmail.com" );
        Console.SetCursorPosition ( 30, 19 );
        Console.ForegroundColor = ConsoleColor.Red;
        Console.Write ( "MUITO OBRIGADO" );
    }
    /*============================================================*/
    void Moldura ( int tam_lin_ini, int tam_lin_fim, int tam_ini_col,
        int tam_fim_col ) {
        int i, c;
        for ( i = tam_lin_ini; i < tam_lin_fim; i++ ) {
            for ( c = tam_ini_col; c < tam_fim_col; c++ ) {
                Console.SetCursorPosition ( c, i );
                Console.BackgroundColor = ConsoleColor.White;
                Console.Write ( " " );
            }
        }
    }
    /*============================================================*/
    void Ini_Array ( ) {
        int i, j;
        //Inicializando array jagged bidimensional de strings
        /*
        //Assim abaixo, cada palavra ocupa uma coluna na matriz
        string [ ] [ ] texto = new string [ 12 ] [ ];
        texto [ 0 ] = new string [ 4 ] { "No", "Meio", "do", "Caminho" };
        texto [ 1 ] = new string [ 4 ] { "Carlos", "Drummond", "de", "Andrade" };
        texto [ 2 ] = new string [ 7 ] { "No", "meio", "do", "caminho", "tinha", "uma", "pedra" };
        texto [ 3 ] = new string [ 7 ] { "Tinha", "uma", "pedra", "no", "meio", "do", "caminho" };
        texto [ 4 ] = new string [ 3 ] { "Tinha", "uma", "pedra" };
        texto [ 5 ] = new string [ 7 ] { "No", "meio", "do", "caminho", "tinha", "uma", "pedra." };
        texto [ 6 ] = new string [ 5 ] { "Nunca", "me", "esquecerei", "desse", "acontecimento" };
        texto [ 7 ] = new string [ 7 ] { "Na", "vida", "de", "minhas", "retinas", "tao", "fatigadas." };
        texto [ 8 ] = new string [ 8 ] { "Nunca", "me", "esquecerei", "que", "no", "meio", "do", "caminho"};
        texto [ 9 ] = new string [ 3 ] { "Tinha", "uma", "pedra" };
        texto[ 10 ] = new string [ 7 ] { "Tinha", "uma", "pedra", "no", "meio", "do", "caminho" };
        texto[ 11 ] = new string [ 7 ] {"No", "meio", "do", "caminho", "tinha", "uma", "pedra."};
       
         */
        //Também pode ser inicialiado assim abaixo:
        //Assim abaixo, cada linha ocupa uma coluna na matriz
        /*
        string [ ] [ ] texto = {
        new string [ ] {"No Meio do Caminho                         "},
        new string [ ] {"Carlos Drummond de Andrade                 "},
        new string [ ] {"No meio do caminho tinha uma pedra         "},
        new string [ ] {"Tinha uma pedra no meio do caminho         "},
        new string [ ] {"Tinha uma pedra                            "},
        new string [ ] {"No meio do caminho tinha uma pedra.        "},
        new string [ ] {"Nunca me esquecerei desse acontecimento    "},
        new string [ ] {"Na vida de minhas retinas tao fatigadas.   "},
        new string [ ] {"Nunca me esquecerei que no meio do caminho "},
        new string [ ] {"Tinha uma pedra                            "},
        new string [ ] {"Tinha uma pedra no meio do caminho         "},
        new string [ ] {"No meio do caminho tinha uma pedra.        "}};
         */

        //Assim abaixo, cada linha ocupa uma coluna na matriz
        string [ ] [ ] texto = new string [ 12 ] [ ];
        texto [ 0 ] = new string [ 1 ] {"No Meio do Caminho                         "};
        texto [ 1 ] = new string [ 1 ] { "Carlos Drummond de Andrade                 " };
        texto [ 2 ] = new string [ 1 ] { "No meio do caminho tinha uma pedra         " };
        texto [ 3 ] = new string [ 1 ] { "Tinha uma pedra no meio do caminho         " };
        texto [ 4 ] = new string [ 1 ] { "Tinha uma pedra                            " };
        texto [ 5 ] = new string [ 1 ] { "No meio do caminho tinha uma pedra.  xx    " };
        texto [ 6 ] = new string [ 1 ] { "Nunca me esquecerei desse acontecimento    " };
        texto [ 7 ] = new string [ 1 ] { "Na vida de minhas retinas tao fatigadas.   " };
        texto [ 8 ] = new string [ 1 ] { "Nunca me esquecerei que no meio do caminho " };
        texto [ 9 ] = new string [ 1 ] { "Tinha uma pedra                            " };
        texto[ 10 ] = new string [ 1 ] { "Tinha uma pedra no meio do caminho         " };
        texto[ 11 ] = new string [ 1 ] { "No meio do caminho tinha uma pedra.        " };

        //Posiciona os textos no console
        Console.SetCursorPosition ( 21, 4 );
        Console.ForegroundColor = ConsoleColor.Blue;
        for ( i = 0; i < texto.Length; i++ ) {
            for ( j = 0; j < texto [ i ].Length; j++ ) {
                Console.Write ( texto [ i ] [ j ] + " " );
            }
            Console.SetCursorPosition ( 21, i + 5 );
        }
        Console.ReadKey ( );
        Console.WriteLine ( );
        Console.SetCursorPosition ( 21, 17 );
        Console.Write ( texto [ 5 ] [ 0 ] );//do
        Console.ReadKey ( );
    }
    /*============================================================*/
    public static void Main ( ) {
        Console.Title = ( "JAGGED ARRAY DE STRING" );
        Arr array = new Arr ( );
        array.Moldura ( 1, 20, 2, 68 );
        Console.SetCursorPosition ( 28, 2 );
        Console.BackgroundColor = ConsoleColor.White;
        Console.ForegroundColor = ConsoleColor.Red;
        Console.Write ( "JAGGED ARRAY DE STRING" );
        //array.Informe ( );
        array.Ini_Array ( );
        //Segura a execução do programa
        Console.ReadKey ( );
    }
}
/*============================================================*/

sexta-feira, 18 de junho de 2021

C# - Marcando ocorrências de múltiplos


A primeira versão deste programa,
foi criada em C++ com o Qt,
e me lembro que me deu bastante trabalho,
porque não é simplesmente pesquisar
os múltiplos, se fosse só isto seria muito fácil,
mas o que agente queria mesmo era marcar
as ocorrências usando um bitimap como fundo;
Depois de várias cabeçadas nós conseguimos,
e depois criemos outra versão no C++ Builder,
ainda em C++, e agora aproveitando um pouco
do tempo que nos sobrou fizemos o mesmo programa
em C# usando o VS Studio da microsoft. 
Veja no vídeo ele funcionando.




        /*============================================================*/
        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, 350, 300 );
            dc.DrawString ( "Samuel Lima ", myFont, myBrush_2, 380, 300 );
            dc.DrawString ( "sa_sp10@hotmail.com ", myFont, myBrush_3, 350, 315 );
        }
        /*============================================================*/
        private void Paint_Imagem ( PaintEventArgs e ) {
            Image newImage = Image.FromFile ( "Moldura_7.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, 379 );
            this.Text = "C# - MÚLTIPLOS MARCANDO OCORRÊNCIAS";
            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# - MÚLTIPLOS MARCANDO OCORRÊNCIAS",
                myFont, myBrush_1, 130, 15 );
            Informe ( e );
        }
        /*============================================================*/
        void FlowLayoutPanel_1 ( int X, int Y, int W, int H ) {
            flowLayoutPanel1.AutoScroll = true;
            this.flowLayoutPanel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.flowLayoutPanel1.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
            8F, System.Drawing.FontStyle.Italic,
            System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            this.flowLayoutPanel1.ForeColor = System.Drawing.Color.Blue;
            this.flowLayoutPanel1.Location = new System.Drawing.Point ( X, Y );
            this.flowLayoutPanel1.Name = "flowLayoutPanel1";
            this.flowLayoutPanel1.Size = new System.Drawing.Size ( W, H );
            this.flowLayoutPanel1.TabIndex = 2;
        }
        /*============================================================*/
        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 Label_1 ( int X, int Y, int W, int H, string st ) {
            //this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font ( "Microsoft Sans Serif",
9.75F, System.Drawing.FontStyle.Italic, 
System.Drawing.GraphicsUnit.Point, ( ( byte ) ( 0 ) ) );
            this.label1.ForeColor = System.Drawing.Color.Blue;
            this.label1.Location = new System.Drawing.Point ( X, Y );
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size ( W, H );
            this.label1.TabIndex = 3;
            this.label1.Text += st;
        }
        /*============================================================*/
        public Form1 ( ) {
            InitializeComponent ( );
        }
        /*============================================================*/
        public void Button_1 ( int X, int Y, int W, int H, string st ) {
            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;
        }
        /*============================================================*/

sábado, 12 de junho de 2021

C# - pesquisando string com método contains


Nome do projeto salvo: DesignerNamao_2

A classe Array Fornece métodos para criar,
manipular, pesquisar e classificar arrays,
servindo assim como a classe base para todos
os arrays suportados pelo C#.
Qualquer um dos elementos de um array,
representa um valor dentro do array,
logo temos num total, uma coleção de
valores iguais, e o cumprimento de
um array é o número total de elementos
que ele pode suportar.
Por padrão, um array tem o zero
como seu limite inferior, e o limite
inferior de um array é o índice de seu
primeiro elemento.
Para este exemplo declaramos um Array de string
de duas dimensões ( Matriz ),
e o inicializamos com um texto contendo várias
poesias famosas criadas por alguns escritores
Brasileiros, e a finalidade do programa
é de apresentar o método Contains(),
da classe string que retorna um valor que indica se 
uma substring especificada ocorre dentro desta string.
usando as regras de comparação especificadas.
Se a palavra digitada no textBox se encontra na matriz
todas as linhas de suas ocorrências são marcadas
com destaque em highlighter .






 /*============================================================*/
        private void OkClick ( object sender, EventArgs e ) {
            str_1 = "";
            str_1 = textBox1.Text;
 
            int i;
            for ( i = 0; i < texto.GetLength ( 0 ); i++ ) {
                label_2 [ i ].BackColor = Color.LightBlue;
                if ( label_2 [ i ].Text.Contains ( str_1 ) ) {
                    label_2 [ i ].BackColor = Color.FromArgb ( 255, 255, 0 );
                    a++;
                }
            }
            label2.Text = "";
            label2.Text = "Encontrado ";
            label2.Text = label2.Text + a;
            label2.Text = label2.Text + " ocorrências da palavra ";
            label2.Text = label2.Text + str_1;
            label_2 [ 0 ].BackColor = Color.FromArgb ( 255, 255, 255 );
            label_2 [ 1 ].BackColor = Color.FromArgb ( 255, 255, 255 );
            label_2 [ 2 ].BackColor = Color.FromArgb ( 255, 255, 255 );
            textBox1.Clear ( );
            textBox1.Focus ( ); 
            a = 0;
        }
        /*============================================================*/


 


sexta-feira, 11 de junho de 2021

C# - Embaralhando e invertendo array de string


O C# possui um método pronto para inverter
um array unidimensional inteiro ou partes
dele, à saber: O método Array.Reverse.
Mas ignoramos isto desta vez e aplicamos
um código clássico utilizado para este objetivo,
e o resultado pode ser visto no vídeo,
e o código do programa pode ser copiado clicando
no link abaixo do vídeo.



        /*============================================================*/
        private void Button1_Click ( object sender, EventArgs e ) {
            System.Drawing.Graphics dc;
            dc = this.CreateGraphics ( );
            //Embaralha o array de string.
            embaralha = Embaralha_Array.Embaralha<string> ( frutas );
            label1.Text = string.Join ( "\r\n", embaralha );
            Inverte_Array ( sender, e );
        }
        /*============================================================*/

sábado, 5 de junho de 2021

C# - pesquisando ocorrências de palavras em frases


Este programa foi adaptado de um exemplo contido
na documentação do C#,  evidentemente muitas
alterações foram feitas por nós mesmo.
e o programa está rodando leve e livre de warnings.
Assista o vídeo e click no link para obter o código 
completo do programa.


        
/*============================================================*/
        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;
            str_2 = " ";
            str_1 = " ";
            textBox1.Clear ( );
            _ = textBox1.Focus ( );
            textBox2.Clear ( );

            //Inserindo um trexo de uma imagem para limpar
            //A linha da impressão da palavra digitada com
            //A pesquisa destacada em highlight
            Image newImage = Image.FromFile ( "FundoBranco.bmp" );
            Point ulCorner;
            ulCorner = new Point ( 100, 160 );

            System.Drawing.Graphics dc;
            dc = this.CreateGraphics ( );
            dc.DrawImage ( newImage, ulCorner );
        }
        /*============================================================*/

sexta-feira, 4 de junho de 2021

C# - pesquisando inteiros em matriz bidimensional

 


Forçamos uma matriz bidimensional de inteiros,
ser preenchida por um contador ascendente num laço for,
mas não achamos muita graça nisto, então criamos
uma rotina manualmente para embaralhar os seus elementos.
Mas como nunca ficamos satisfeito com o pouco,
declaramos um objeto imagem e desenhamos com
a chamada do evento OnPaint, sendo que o nosso desejo
era que esta imagem de uma pequena esfera em 3D se
tornasse fundo de cada número imprimido pela matriz,
deu tudo certo! só que a ousadia não tem limites,
então adicionamos mais uma imagem de outra esfera
em 3D, para que se torne fundo dos números encontrados
pela pesquisa realizada pelo programa, ao mesmo tempo
que estes valores são novamente embaralhados a cada
click no botão "Ok".
Assista no vídeo estas coisas acontecendo.





        /*============================================================*/
        private void Button1_Click ( object sender, EventArgs e ) {
            System.Drawing.Graphics dc;
            dc = this.CreateGraphics ( );
            Font myFont = new System.Drawing.Font ( "Consolas", 11,
                FontStyle.Bold );

            Brush myBrush_1 = new SolidBrush ( Color.Red );
            Brush myBrush_2 = new SolidBrush ( Color.Black );
            int i, j, r, y, temp;
            Random rnd = new Random ( );

            for ( i = 0; i < 6; i++ ) {
                for ( j = 0; j < 6; j++ ) {
                    r = rnd.Next ( 1, 6 );
                    y = rnd.Next ( 1, 6 );
                    temp = A [ i, j ];
                    A [ i, j ] = A [ r, y ];
                    A [ r, y ] = temp;
                }
            }

            Image newImage = Image.FromFile ( "Bal.bmp" );
            Image newImage_2 = Image.FromFile ( "Bal_green_claro.bmp" );

            for ( r = 0; r < 6; r++ ) {
                for ( y = 0; y < 6; y++ ) {

                    Point ulCorner;
                    ulCorner = new Point ( 200 + ( y * 35 ), 37 + ( r * 35 ) );
                    dc.DrawImage ( newImage, ulCorner );

                    if ( A [ r, y ] <= 9 ) {
                        dc.DrawString ( "0",
                        myFont, myBrush_2, 204 + ( y * 35 ), 44 + ( r * 35 ) );

                        dc.DrawString ( "" + A [ r, y ],
                        myFont, myBrush_2, 212 + ( y * 35 ), 44 + ( r * 35 ) );
                    }
                    if ( A [ r, y ] > 9 ) {
                        dc.DrawString ( "" + A [ r, y ],
                        myFont, myBrush_2, 205 + ( y * 35 ), 44 + ( r * 35 ) );
                    }
                }
            }
            button1.Enabled = false;
            button2.Visible = true;

            Button_1 ( 200, 260, 80, 22, "Pesquisa" );
            textBox1.Visible = true;
            TextBox_1 ( 300, 260, 30, 10 );
            Button_2 ( 360, 260, 40, 22, "Ok" );
            _ = textBox1.Focus ( );
        }
        /*============================================================*/