I need different ways to rearrange characters within a string, how do I do this?

3

I would like answers in C, C #, or just an algorithm, but preferably an implementation already in the C # language because that's what I'm using.

For example, suppose I have to find out if a number is read in the same way both ways - a silly programming exercise that I can never solve.

4004

I figured I could do the following:

  • Convert to string.
  • I put the string in an array of characters.
  • Using an appropriate function, I find the size of the array.
  • I create another array of the same size.
  • Copy bytes from array1 to array2 , in reverse order (position 0 in array1 becomes last of array2 , position 1 becomes penultimate, etc ...)
  • I compare the resulting strings, if they are the same the number is a palindrome.
  • I think this works, but besides not knowing how to do it in the language, I think there must be some simpler way.

        
    asked by anonymous 07.09.2015 / 20:57

    4 answers

    1

    Simple, use the reverse to convert the string into an array in reverse and compare with the original value.

    public bool EhPalindromo(string text)
    {
         var reverseText = string.Join("", text.ToLower().Reverse());
         return reverseText == text;
    }
    
        
    09.09.2015 / 03:30
    7

    You do not have to move the text, just compare each character starting from the first with the last, then the second with the penultimate, and so on. You need to compare only halfway since the after half comparison would only repeat what was compared in reverse:

    using static System.Console;
    
    public class Program {
        public static void Main() {
            WriteLine(EhPalindromo("4004"));
            WriteLine(EhPalindromo("4002"));
        }
        public static bool EhPalindromo(string texto) {
            //Inicia no final e vai até a metade do final
            for (int i = texto.Length - 1; i > texto.Length / 2; i--) {
                //compara o caractere atual com o inverso dele
                if (texto[i] != texto[texto.Length - i - 1]) {
                    //encontrou uma diferença, pode encerrar sabendo que não bate
                    return false;
                }
            }
            //se chegou até aqui é porque houve coincidência total
            return true;
        }
    }
    

    See working on dotNetFiddle .

    Surely it could have been done with a simpler code using something ready but I believe the question is precisely to learn how to do an algorithm that you do manually.

        
    07.09.2015 / 21:07
    1

    I once had to solve a similar problem in C, here's what I did:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    //retonra o tamanho de uma string delimitada por '
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    //retonra o tamanho de uma string delimitada por '%pre%',
    //ou oturo caracter < 32 na ASCII.
    //Parametro: string a ser verificado o tamanho.
    int sizeofString(char* str){
        int i = 0;
        for(i;str[i] >= 32;i++);
        return i;
    }
    
    //retorna true(1) caso as duas strings sejam inversas.
    //Parametros: str1 e str2 sao as strings a serem analisadas.
    int numerosInversos(char* str1, char* str2){
        int tam = sizeofString(str1);
        if(tam != sizeofString(str2))return 0;
        else{
             int i = 0;
             for(i;i<tam;i++)
                   if(str1[i] != str2[tam-i-1]) return 0;          
             return 1;      
        }    
    }
    
    int main(){
        char num1[10],num2[10];
        strcpy(num1,"4004");
    
        if(numerosInversos(num1,num1))printf("\nIguais\n");
        else printf("\nDiferentes\n");
    
        system("pause");    
        return 0;}
    
    ', //ou oturo caracter < 32 na ASCII. //Parametro: string a ser verificado o tamanho. int sizeofString(char* str){ int i = 0; for(i;str[i] >= 32;i++); return i; } //retorna true(1) caso as duas strings sejam inversas. //Parametros: str1 e str2 sao as strings a serem analisadas. int numerosInversos(char* str1, char* str2){ int tam = sizeofString(str1); if(tam != sizeofString(str2))return 0; else{ int i = 0; for(i;i<tam;i++) if(str1[i] != str2[tam-i-1]) return 0; return 1; } } int main(){ char num1[10],num2[10]; strcpy(num1,"4004"); if(numerosInversos(num1,num1))printf("\nIguais\n"); else printf("\nDiferentes\n"); system("pause"); return 0;}

    I know that in C # there are functions for transforming integers into strings ([integer] .ToString (), if I'm not mistaken).

        
    09.09.2015 / 22:08
    1

    Making a change in @Kevin's answer I think it would do more right on non-numeric string usage issues too:

    public bool EhPalindromo(string texto)
    {
         var textoAoContrario = String.Join("", texto.ToLower().Reverse());
         return textoAoContrario == texto.ToLower();
    }
    

    The main modification is for .ToLower() in the variable texto also, since the same function is used in the reverse text.

        
    09.09.2015 / 22:31