i’m trying to write a program in which a word as a string is provided as an input and i have to rearrange the word such that it just changes the order of the letters in a word by moving
all the vowels to the end, keeping them in the same order as they appeared in the original word
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string word = "application";
char[] letters = word.ToCharArray();
char x = new char { };
for (int j = 0; j < letters.Length; j++)
{
if ((letters[j] == 'a') | (letters[j] == 'e' ) | (letters[j] == 'i' ) | (letters[j] == 'o' ) | (letters[j]
== 'u'))
{
for (int i = 0; i < letters.Length - 1; i++)
{
x = letters[i];
letters[i] = letters[i + 1];
letters[i + 1] = x;
}
}
}
string s = new string(letters);
Console.WriteLine(s);
}
}
}
the output of the program is
ationaplic
but the intended output of program is
pplctnaiaio
Why is my code not producing my intended output?
The edited working code is
namespace VowelSort
{
class Program
{
static void Main(string[] args)
{
string word = "application";
char[] letters = word.ToCharArray();
char x = new char { };
int count = 0;
for (int j = 0; j < letters.Length - count; j++)
{
if ((letters[j] == 'a') | (letters[j] == 'e') | (letters[j] == 'i') | (letters[j] == 'o') | (letters[j] == 'u') | (letters[j] == 'A') | (letters[j] == 'E') | (letters[j] == 'I') | (letters[j] == 'O') | (letters[j] == 'U'))
{
for (int i = j; i < letters.Length - 1; i++)
{
x = letters[i];
letters[i] = letters[i + 1];
letters[i + 1] = x;
}
count++;
j--;
}
}
string s = new string(letters);
Console.WriteLine(s);
Console.WriteLine(count);
}
}
}
There are three problems I found here:
0so you always move the first character to the end. Start it atjinstead.j.Try to implement these changes yourself, but if you get stuck I can give you some pointers.
Once you have this working, you might like to speed up your inner loop by realising you don’t have to perform multiple pairwise swaps – you can just note the vowel you’ve found, move everything after it up one character, and then insert the vowel at the end.