how swap adjacent chars in a given string without using string builder or any method
ex::
input: Tapan
output: atapn like
This is My Code
C#
Console.WriteLine("enter a string");
string sS = Console.ReadLine();
string sss = "";
int i, j;
for (i = 0; i < sS.Length; i++)
{sss += sS[i + 1];sss += sS[i];
}
Console.WriteLine(sss);
Jaya PrakashRank #1,293 · 1.3K reputationPosted Sep 15, 2022, 10:02 AM EDT
Thank you sir for ur help
Jignesh KumarRank #91 · 22.9K reputationPosted Sep 15, 2022, 2:49 AM EDT
Hi Jaya Prakash,
Please find below and try to debug and understand,
string input = "Tapan"; //Sample String string output = string.Empty; char[] characters = input.ToCharArray(); for (int i = 0; i < characters.Length; i++) { if (i % 2 == 0) { if ((i + 1) < characters.Length) { output += characters[i + 1]; } output += characters[i]; } }Uday DodiyaRank #239 · 10.3K reputationPosted Sep 15, 2022, 4:50 AM EDT
Hi Jaya
Try Following Code, you can get your output
Code 1 :
Console.WriteLine("Enter a string : "); string sS = Console.ReadLine(); string sss = ""; for (int i = 0; i < sS.Length; i = i + 2) { if((i+1) < sS.Length) { sss += sS[i + 1]; } sss += sS[i]; } Console.WriteLine(sss);Code 2 :
Console.WriteLine("Enter a string : "); string sS = Console.ReadLine(); string sss = ""; int i = 0; for (i = 0; i < sS.Length-1; i = i + 2) { sss += sS[i + 1]; sss += sS[i]; } sss += sS[i]; Console.WriteLine(sss);