Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How do i move the character at the end of a string to the beginning of the string.

E.g

string a = "stack";

I want that string to be replaced with "kstac"

Thanx
Posted
Updated 25-Jun-12 5:22am
v2
Comments
Tim Corey 25-Jun-12 10:18am    
What have you tried? What is the context of this?

C#
string s = string.Format("{0}{1}", s.Substring(1, s.Length - 1), s[s.Length - 1]);


would be better

C#
string s = "stack";
int lengthOfMovingPart =  1;
s = string.Format("{0}{1}", s.Substring(s.Length - lengthOfMovingPart),s.Substring(0, s.Length - lengthOfMovingPart));
 
Share this answer
 
v4
Comments
Tim Corey 25-Jun-12 10:21am    
Simple yet effective. Nice job.
Raidzen10 25-Jun-12 11:11am    
Have you tried it? Does it return "kstac"?. Because i get "tackk".
BoxyBrown 25-Jun-12 11:45am    
I think i've mistake with order of params. I'll check it now. Sorry
BoxyBrown 25-Jun-12 11:49am    
s = string.Format("{0}{1}", s.Substring(s.Length - lengthOfMovingPart),s.Substring(0, s.Length - lengthOfMovingPart));

this is correct
You can simply use string Substring method for this. But you may need to handle when input string null or empty case and when string length is 1 as well.

Since already post answer with Substring method, here is a Linq solution.

C#
public string ProcessText(string input)
{
    if (!string.IsNullOrEmpty(input) && input.Length > 1)
    {
        return input.Last() + input.Remove(input.Length - 1);
    }
    return input;
}
 
Share this answer
 
v3
Try this :
C#
string s = "stack";
char[] cc = s.ToCharArray();
Array.Reverse(cc);
string rev = new string(cc);
 
Share this answer
 
Comments
Tim Corey 25-Jun-12 10:19am    
That would result in "kcats" but the OP wants "kstac".
Mehdi Gholam 25-Jun-12 10:26am    
Right you are, reminds me of the research done where people read the first and last characters of words and make up the rest :)
Tim Corey 25-Jun-12 10:27am    
:) Yep, it is easy to do.

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