Click here to Skip to main content
15,886,547 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi,

how to read characters from right side in string............


Please suggest

What I have tried:

string="samplestring";
string.Substring(string.Length - 4, 4);

it gives the result, but from left side... i want to read 4 characters from right side.
Posted
Updated 12-May-16 2:20am
Comments
Karthik_Mahalingam 12-May-16 7:50am    
what is your expected output ?

try this

C#
string input = "samplestring";
          var str = input.Substring(input.Length - 4, 4);
          string output = "";
          for (int i = str.Length -1; i >= 0; i--)
              output += str[i].ToString();

// output will be gnir
 
Share this answer
 
Comments
CPallini 12-May-16 9:33am    
5. It looks correct, to me.
Karthik_Mahalingam 12-May-16 9:44am    
Thanks CPallini
  1. Reverse the string
  2. Take the wanted characters from the left


See c# - Best way to reverse a string - Stack Overflow[^].
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 12-May-16 8:49am    
Do you mean
3. Reverse the result
? :-) :-)

I understand your joke, but not sure about other members...

—SA
CPallini 12-May-16 9:32am    
It is not a joke, actually.
Sergey Alexandrovich Kryukov 12-May-16 10:41am    
Really? I know it would work, of course, but not without item 3, and it would be ridiculous in terms of performance... :-)
—SA
CPallini 12-May-16 12:52pm    
No, you haven't to reverse the result, because that's exactly what the OP searches for: the string read from the right, namely 'gnir'.
Sergey Alexandrovich Kryukov 12-May-16 12:57pm    
I see no indication of that, but if it's really so, your solution is pretty good (perhaps extracting the substring first and then reversing it would be better, but your solution would be more elegant.)
—SA
Your sample code will not even compile, let alone run, so it is difficult to see how you manage to get any result. The correct code would be something like:
C#
string foo ="samplestring";
string bar = foo.Substring(foo.Length - 4, 4);
Console.WriteLine("Substring: {0}", bar);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900