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

Asked

Viewed 872 times

4

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 the same way in both directions - a silly programming exercise that I can never solve.

4004

I figured I could do the following:

  1. Convert to string.
  2. I place the string in an array of characters.
  3. Using an appropriate function I discover the size of the array.
  4. I create another array of the same size.
  5. I copy bytes of array1 to the array2, in reverse order (position 0 in array1 becomes the last of array2, position 1 becomes penultimate, etc...)
  6. I compare the resulting strings, if they are equal the number is a palindrome.

I think it works, but besides not knowing how to do it in language, I think there must be some simpler way.

4 answers

7

You don’t have to keep fiddling with 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 half as long as the comparison after half would only repeat what was compared inversely:

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

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Certainly it could have been done with a simpler code using something ready but I believe the question is precisely how to make an algorithm that does manually.

  • 1

    Why texto.Substring(i, 1) and not texto[i]? It is more efficient to compare the character than to create and allocate 2*n sub strings. One more thing, the breakage condition can be i > texto.Length /2. And since OP is not experienced in either programming or language, I think a Portuguese explanation of the algorithm would help.

  • It’s just that I based myself on an algorithm that I already had in another language. In fact I can optimize.

1

Once I had to solve a similar problem in C, follow what I did:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//retonra o tamanho de uma string delimitada por '\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 the transformation of integers into strings ([integer value]. Tostring(), if I’m not mistaken).

1

Making a change to @Kevin’s reply I think it would be more right in using non-numeric strings as well:

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

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

1


Simple, use Reverse to convert the string into a reverse array and compare it to the original value.

public bool EhPalindromo(string text)
{
     var reverseText = string.Join("", text.ToLower().Reverse());
     return reverseText == text;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.