Got stuck with this.. can you please explain what is happening in it? or give me any link!
String s1="C# Example";
Char[] s3 = s1.ToCharArray();
Console.WriteLine("S3 : {0}",s3);
I want to display the Character which is converted. Output displayed is System.Char[]. Now i need to do some changes, but what is that ?
It is possible in two ways.
1) I need to Change it to String, before i'm going to Print.
Or
2) I need to print it with Char by defining the index, (i.e) s3[0];
Am i correct. Anything More?
Solution A:
If you want to display the characters individually on console then you need to get each character separately and display it using a loop.
foreach(char ch in s3)
{
Console.WriteLine("S3 : {0}", ch);
}
or, using for-loop,
for (int i = 0; i < s3.Length; i++)
{
Console.WriteLine("S3 : {0}", s3[i]);
}
Solution B : There's anbther way that I prefer which might not be helpful for you but for those who always looks into better solutions it can be an option also.
Use Extension methods,
Add this class with the extension method in your solution,
public static class DisplayExtension
{
public static string DisplayResult(this string input)
{
var resultString = "";
foreach (char ch in input.ToCharArray())
{
resultString += "S3 : " + ch.ToString() + "\n";
}
return resultString;
}
}
And call the DisplayResult() extension method from your program like this,
Console.WriteLine(s1.DisplayResult());
This will give you the same result but extend the re-usability of your code without writing the for loop for all the repeated situation.