Como reverter uma string em C ++, Python e JavaScript

Como reverter uma string em C ++, Python e JavaScript

Como programador, você provavelmente enfrentou uma situação que exige a reversão de uma string. Reverter uma string é uma das situações mais comuns que os programadores enfrentam ao aprender a codificar. Você pode reverter uma string usando funções integradas ou escrevendo sua própria implementação da função reversa.





Neste artigo, você aprenderá sobre diferentes métodos para reverter uma string em C ++, Python e JavaScript.





Métodos diferentes para reverter uma string em C ++

Você pode reverter uma string em C ++ usando estes métodos:





Reverter uma string em C ++ usando a função reverse () integrada

Abaixo está o programa C ++ para reverter uma string usando o reverter() função:

// C++ implementation to reverse a string
// using inbuilt function: reverse()
#include
using namespace std;
// Driver Code
int main()
{
string str1 = 'MUO';
string str2 = 'Welcome to MUO';
string str3 = 'She sells seashells by the seashore';
cout << 'Input string:' << endl;
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
reverse(str1.begin(), str1.end());
reverse(str2.begin(), str2.end());
reverse(str3.begin(), str3.end());
cout << 'Reversed string: ' << endl;
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
return 0;
}

Saída:



Input string:
MUO
Welcome to MUO
She sells seashells by the seashore
Reversed string:
OUM
OUM ot emocleW
erohsaes eht yb sllehsaes slles ehS

Reverter uma string em C ++ trocando caracteres

Abaixo está o programa C ++ para reverter uma string trocando caracteres:

// C++ implementation to reverse a string
// by swapping characters
#include
using namespace std;
// Own implementation of a function to reverse a string
void reverseString(string& str)
{
int size = str.size();
for(int i=0, j=size-1; i {
swap(str[i], str[j]);
}
}
// Driver Code
int main()
{
string str1 = 'MUO';
string str2 = 'Welcome to MUO';
string str3 = 'She sells seashells by the seashore';
cout << 'Input string:' << endl;
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
reverseString(str1);
reverseString(str2);
reverseString(str3);
cout << 'Reversed string: ' << endl;
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
return 0;
}

Saída:





Input string:
MUO
Welcome to MUO
She sells seashells by the seashore
Reversed string:
OUM
OUM ot emocleW
erohsaes eht yb sllehsaes slles ehS

Reverter uma string em C ++ usando iteradores reversos com um construtor

Abaixo está o programa C ++ para reverter uma string usando iteradores reversos com um construtor:

// C++ implementation to reverse a string
// using constructor
#include
using namespace std;
int main()
{
string str1 = 'MUO';
string str2 = 'Welcome to MUO';
string str3 = 'She sells seashells by the seashore';

cout << 'Input string:' << endl;
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
// Using reverse iterators to reverse a string
string reversedStr1 = string(str1.rbegin(), str1.rend());
string reversedStr2 = string(str2.rbegin(), str2.rend());
string reversedStr3 = string(str3.rbegin(), str3.rend());
cout << 'Reversed string: ' << endl;
cout << reversedStr1 << endl;
cout << reversedStr2 << endl;
cout << reversedStr3 << endl;
return 0;
}

Saída:





por que o uso da CPU é tão alto
Input string:
MUO
Welcome to MUO
She sells seashells by the seashore
Reversed string:
OUM
OUM ot emocleW
erohsaes eht yb sllehsaes slles ehS

Reverter uma string em C ++ usando uma string temporária

Abaixo está o programa C ++ para reverter uma string usando uma string temporária:

// C++ implementation to reverse a string
// using a temporary string
#include
using namespace std;
// Function to reverse a string using a temporary string
string reverseString(string str)
{
int size = str.size();
string tempStr;
for(int i=size-1; i>=0; i--)
{
tempStr.push_back(str[i]);
}
return tempStr;
}
// Driver Code
int main()
{
string str1 = 'MUO';
string str2 = 'Welcome to MUO';
string str3 = 'She sells seashells by the seashore';
cout << 'Input string:' << endl;
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
str1 = reverseString(str1);
str2 = reverseString(str2);
str3 = reverseString(str3);
cout << 'Reversed string: ' << endl;
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;

return 0;
}

Saída:

Input string:
MUO
Welcome to MUO
She sells seashells by the seashore
Reversed string:
OUM
OUM ot emocleW
erohsaes eht yb sllehsaes slles ehS

Relacionado: Como encontrar vogais, consoantes, dígitos e caracteres especiais em uma string

Métodos diferentes para reverter uma string em Python

Você pode reverter uma string em Python usando estes métodos:

Reverter uma string em Python usando a sintaxe de fatia estendida

Abaixo está o programa Python para reverter uma string usando uma sintaxe de fatia estendida:

# Python implementation to reverse a string
# using extended slice syntax
def reverseString(str):
return str[::-1]

str1 = 'MUO';
str2 = 'Welcome to MUO';
str3 = 'She sells seashells by the seashore';
print('Input string:')
print(str1)
print(str2)
print(str3)
str1 = reverseString(str1)
str2 = reverseString(str2)
str3 = reverseString(str3)
print('Reversed string:')
print(str1)
print(str2)
print(str3)

Saída:

Input string:
MUO
Welcome to MUO
She sells seashells by the seashore
Reversed string:
OUM
OUM ot emocleW
erohsaes eht yb sllehsaes slles ehS

Reverter uma string em Python usando recursão

Abaixo está o programa Python para reverter uma string usando recursão:

Relacionado: O que é recursão e como usá-lo?

# Python implementation to reverse a string
# using recursion
def reverseString(str):
if len(str) == 0:
return str
else:
return reverseString(str[1:]) + str[0]

str1 = 'MUO';
str2 = 'Welcome to MUO';
str3 = 'She sells seashells by the seashore';
print('Input string:')
print(str1)
print(str2)
print(str3)
str1 = reverseString(str1)
str2 = reverseString(str2)
str3 = reverseString(str3)
print('Reversed string:')
print(str1)
print(str2)
print(str3)

Saída:

Input string:
MUO
Welcome to MUO
She sells seashells by the seashore
Reversed string:
OUM
OUM ot emocleW
erohsaes eht yb sllehsaes slles ehS

Reverter uma string em Python usando o método reversed () integrado

Abaixo está o programa Python para reverter uma string usando o sistema integrado invertido () método:

# Python implementation to reverse a string
# using reversed method()
def reverseString(str):
str = ''.join(reversed(str))
return str

str1 = 'MUO';
str2 = 'Welcome to MUO';
str3 = 'She sells seashells by the seashore';
print('Input string:')
print(str1)
print(str2)
print(str3)
str1 = reverseString(str1)
str2 = reverseString(str2)
str3 = reverseString(str3)
print('Reversed string:')
print(str1)
print(str2)
print(str3)

Saída:

Input string:
MUO
Welcome to MUO
She sells seashells by the seashore
Reversed string:
OUM
OUM ot emocleW
erohsaes eht yb sllehsaes slles ehS

Reverter uma string em Python usando uma string temporária

Abaixo está o programa Python para reverter uma string usando uma string temporária:

# Python implementation to reverse a string
# using a temporary string
def reverseString(str):
tempStr = ''
for s in str:
tempStr = s + tempStr
return tempStr

str1 = 'MUO';
str2 = 'Welcome to MUO';
str3 = 'She sells seashells by the seashore';
print('Input string:')
print(str1)
print(str2)
print(str3)
str1 = reverseString(str1)
str2 = reverseString(str2)
str3 = reverseString(str3)
print('Reversed string:')
print(str1)
print(str2)
print(str3)

Saída:

Input string:
MUO
Welcome to MUO
She sells seashells by the seashore
Reversed string:
OUM
OUM ot emocleW
erohsaes eht yb sllehsaes slles ehS

Métodos diferentes para reverter uma string em JavaScript

Você pode reverter uma string em JavaScript usando estes métodos:

Relacionado: Como criar seu primeiro aplicativo React com JavaScript

Reverter uma string em JavaScript usando recursão

Abaixo está o programa JavaScript para reverter uma string usando recursão:

// JavScript implementation to reverse a string
// using recursion
function reverseString(str) {
if (str === '') {
return '';
} else {
return reverseString(str.substr(1)) + str.charAt(0);
}
}
str1 = 'MUO';
str2 = 'Welcome to MUO';
str3 = 'She sells seashells by the seashore';
document.write('Input string:
');
document.write(str1 + '
');
document.write(str2 + '
');
document.write(str3 + '
');
str1 = reverseString(str1);
str2 = reverseString(str2);
str3 = reverseString(str3);
document.write('Reversed string:
');
document.write(str1 + '
');
document.write(str2 + '
');
document.write(str3 + '
');

Saída:

Input string:
MUO
Welcome to MUO
She sells seashells by the seashore
Reversed string:
OUM
OUM ot emocleW
erohsaes eht yb sllehsaes slles ehS

Reverter uma string em JavaScript usando métodos integrados

Abaixo está o programa JavaScript para reverter uma string usando métodos integrados:

// JavaScript implementation to reverse a string
// using inbuilt methods
function reverseString(str) {
return str.split('').reverse().join('');
}
str1 = 'MUO';
str2 = 'Welcome to MUO';
str3 = 'She sells seashells by the seashore';
document.write('Input string:
');
document.write(str1 + '
');
document.write(str2 + '
');
document.write(str3 + '
');
str1 = reverseString(str1);
str2 = reverseString(str2);
str3 = reverseString(str3);
document.write('Reversed string:
');
document.write(str1 + '
');
document.write(str2 + '
');
document.write(str3 + '
');

Saída:

Input string:
MUO
Welcome to MUO
She sells seashells by the seashore
Reversed string:
OUM
OUM ot emocleW
erohsaes eht yb sllehsaes slles ehS

Reverter uma string em JavaScript usando uma string temporária

Abaixo está o programa JavaScript para reverter uma string usando uma string temporária:

// JavScript implementation to reverse a string
// using a temporary string
function reverseString(str) {
var size = str.length;
tempStr = '';
for(let i=size-1; i>=0; i--)
{
tempStr += str[i];
}
return tempStr;
}
str1 = 'MUO';
str2 = 'Welcome to MUO';
str3 = 'She sells seashells by the seashore';
document.write('Input string:
');
document.write(str1 + '
');
document.write(str2 + '
');
document.write(str3 + '
');
str1 = reverseString(str1);
str2 = reverseString(str2);
str3 = reverseString(str3);
document.write('Reversed string:
');
document.write(str1 + '
');
document.write(str2 + '
');
document.write(str3 + '
');

Saída:

Input string:
MUO
Welcome to MUO
She sells seashells by the seashore
Reversed string:
OUM
OUM ot emocleW
erohsaes eht yb sllehsaes slles ehS

Aprenda a manipulação de cordas

Para resolver problemas de entrevista relacionados a strings, você deve saber como manipular uma string. Você pode manipular uma string em qualquer linguagem de programação, como C ++, Python, JavaScript, Java, C, etc.

Python fornece a sintaxe mais fácil de entender para manipular uma string. Se manipular string parece difícil para você, experimente o Python; é enganosamente simples.

Compartilhado Compartilhado Tweet O email Aprendendo Python? Veja como manipular strings

Usar e manipular strings em Python pode parecer difícil, mas é enganosamente simples.

Leia a seguir
Tópicos relacionados
  • Programação
  • JavaScript
  • Pitão
  • Tutoriais de codificação
Sobre o autor Yuvraj Chandra(60 artigos publicados)

Yuvraj é estudante de graduação em Ciência da Computação na Universidade de Delhi, na Índia. Ele é apaixonado por Full Stack Web Development. Quando não está escrevendo, ele está explorando a profundidade de diferentes tecnologias.

mac terminal comandos cheat sheet pdf
Mais de Yuvraj Chandra

Assine a nossa newsletter

Junte-se ao nosso boletim informativo para dicas de tecnologia, análises, e-books grátis e ofertas exclusivas!

Clique aqui para se inscrever