-4

Id like to create a method: public static string FrontBack(string str) {}

This method should exchange the first char for the last char.

for example : Console.WriteLine(FrontBack("code"));

So in this case i'd like to replace char "c" with "e" and the result should be eodc.

coze
  • 95
  • 2
  • 6
  • 3
    Any attempts so far? Why don't you use `Substring` + some simple calculations? – Andrey Korneyev Apr 09 '15 at 15:15
  • 4
    You should attempt to solve this problem first, and tell us what you tried. Otherwise, especially for a relatively simple question like this, it sounds like a "give me code plz" non-question. – Tim S. Apr 09 '15 at 15:15
  • I give you a hint: you can iterate over a string since it is also a char array. So you can do something like this foreach(char s in stringVar){ do sth here } – fabricio Apr 09 '15 at 15:15
  • And http://codeblog.jonskeet.uk/2009/11/02/omg-ponies-aka-humanity-epic-fail/, begin with *Tony, I’d like you to write some code to reverse a string.* – xanatos Apr 09 '15 at 15:17
  • @fabricio No need to use a for since he just wants to swap first and last characters – Arthur Rey Apr 09 '15 at 15:17
  • @ArthurRey yeah.. you're right. But the whole idea of it is that he can treat the string as an array. – fabricio Apr 09 '15 at 15:19
  • 1
    @xanatos, I prefer this answer: http://stackoverflow.com/a/15111719/2850543. Is there a reason you choose the other? – Millie Smith Apr 09 '15 at 15:22
  • @MillieSmith Because I hadn't seen it :-) – xanatos Apr 09 '15 at 15:23
  • Hah :). Fair enough @xanatos – Millie Smith Apr 09 '15 at 15:24
  • @AndyKorneyev till now i'm trying to get this working: 'char front = char.Parse(str.Substring(0,1)); char back = str[s.Length - 1]; return back + str + front;' – coze Apr 09 '15 at 15:51

6 Answers6

1

Your question is a little too much easy... So I will give you extra-complex code:

public static string ExchangeFirstLast(string str)
{
    var lst = new List<string>();
    var enumerator = StringInfo.GetTextElementEnumerator(str);

    while (enumerator.MoveNext())
    {
        lst.Add(enumerator.GetTextElement());
    }

    if (lst.Count >= 2)
    {
        string temp = lst[0];
        lst[0] = lst[lst.Count - 1];
        lst[lst.Count - 1] = temp;
    }

    string str2 = string.Concat(lst);
    return str2;
}

This code will try to solve the problem with non-BMP unicode characters and composing unicode characters. See http://codeblog.jonskeet.uk/2009/11/02/omg-ponies-aka-humanity-epic-fail/ from Tony, I’d like you to write some code to reverse a string

xanatos
  • 109,618
  • 12
  • 197
  • 280
0
public static string FrontBack(string str) {
    int len = str.Length;
    return str[len-1] + str.Substring(1,len-2) + str[0]; 
}
Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
agentshowers
  • 170
  • 8
0

Simplest would be:

string str = "code";
string FrontBackString = str.Length >= 2 ? 
                        str[str.Length - 1] + str.Substring(1, str.Length - 2) + str[0] 
                        : str;
CriketerOnSO
  • 2,600
  • 2
  • 15
  • 24
0
private static string FrontBack(string str)
{
    if (string.IsNullOrWhiteSpace(str)) 
        throw new ArgumentNullException("str");

    if (str.Length == 1) return str;

    var first = str[0];
    var last = str[str.Length - 1];
    return last + str.Substring(1, str.Length - 2) + first;
}
Millie Smith
  • 4,536
  • 2
  • 24
  • 60
Tomasz Jaskuλa
  • 15,723
  • 5
  • 46
  • 73
0

On a sportsmanship note, a one liner using StringBuilder (no checks for string validity though):

private static string FrontBack(string str)
{
    return (new StringBuilder(str).Remove(str.Length - 1, 1)
        .Remove(0, 1).Insert(0, str[str.Length - 1])
        .Insert(str.Length - 1, str[0])).ToString();
}

// 1. Remove last character
// 2. Remove first character
// 3. Append last character to beginning
// 4. Append first character to the end 
eYe
  • 1,695
  • 2
  • 29
  • 54
0

I have something like this for you:

internal class Program
    {
        static void Main(string[] args)
        {
            
            // on this String we want make the changes
            String Given= "Rubbish!";

            //here we calл the method
            Console.WriteLine(SwapTheDigits(Given));

            // this only to prevent the console from closing
            Console.ReadLine();

        }
        public static String SwapTheDigits(String given)
        {
            // here we declare the middle part of the string
            String MiddlePart = "";
            if (given == null)
            {
                // if the user is comming up with the empty string
                // the error will be thrown
                throw new ArgumentNullException("String can't be empty");
            }
            else
            {
                // and here is basically the whole "magic"
                // You save the first digit of String Array into the First variable
               // thw last into the last one

                char First = given[0];
                char Last = given[given.Length - 1];

                // there are several overloads of the substring method
                // here I'm using what fits the best for this task, to cut the first and the last (two) digits.
                MiddlePart = given.Substring(1,given.Length - 2);
                
                // and here we return the string with swaped digits.
                return Last + MiddlePart + First;
                
            }           
        }
    }

I hope this helps. There are, of course, many more solutions out there. Even better then mine. As I am a beginner myself, this is one of my first attempts. For the same reason i'm not sure if my explanation helps you. You always welcome to ask, if you need more suport. Thank you @Jeremy Caney for guiding.

miles
  • 1
  • 2
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Apr 06 '23 at 00:15