Hi all,
I have written the code below to reverse the words in the string or sentence.
Please run this in your system and check whether it is correct:
class Palindrome
{
public static void Main()
{
string text = "C Sharp Corner ";
Console.WriteLine(PrintWordInReverse(text));
}
//Method to reverse the order
static string PrintWordInReverse(string str)
{
string revWord = string.Empty;
string finalsentence = string.Empty;
for (int i = 0; i < str.Length; i++)
{ if(str[i]!=null)
{
revWord=str[i]+revWord;
}
else
{
revWord=revWord+"";
finalsentence=finalsentence+revWord;
revWord=string.Empty;
}
}
if (revWord != string.Empty)
{
}
return finalsentence;
}
}
Loading
VulpesPosted Jun 26, 2012, 11:29 AM
Here's my own solution for that option which uses no built-in functions but is relatively long winded as a result:
Jignesh's solution works fine for option 2.
For option 3, this should work:
rani m mkPosted Jun 30, 2012, 12:24 AM
Satyapriya NayakPosted Jun 26, 2012, 9:59 AM
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Reverse_string
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string s1 = "C Sharp Corner";
string[] s2 = s1.Split(' ');
Array.Reverse(s2);
string s3 = String.Join(" ", s2);
MessageBox.Show(s3);
}
}
}
Thanks
VulpesPosted Jun 26, 2012, 9:19 AM
Jignesh TrivediPosted Jun 26, 2012, 7:17 AM
Just Replace your PrintWordInReverse fuction with.
static string PrintWordInReverse(string str)
{
string finalsentence = string.Empty;
for (int i = str.Length - 1; i >= 0; i--)
{
finalsentence = finalsentence + str[i];
}
return finalsentence;
}
hope this will help you.
Santhosh Kumar JayaramanPosted Jun 26, 2012, 7:12 AM
revWord=str[i]+revWord;
finalsentence = revWord;