swap the last and first characters in a string

Viewed 83

I have a code that:

  • reads a text file

  • replaces all lines who looks like "xx.xx.xx" to "date"

  • saves a new file with changes.

    static void Main(string[] args)
     {
         RegexOptions options = RegexOptions.None;
         Regex regex1 = new Regex(@"\d{2}\.\d{2}\.\d{2}", options);
    
         string FilePath = @"C:\Users\User\Desktop\download1.txt";
         string OutputhFilePath = @"C:\Users\User\Desktop\nf\download11.txt";
    
         List<string> lines = new List<string>();
         lines = File.ReadAllLines(FilePath).ToList();
         var sb = new StringBuilder();
    
         foreach (string line in lines)
         {
             string line2 = regex1.Replace(line, "date");
             sb.AppendLine(line2);
             File.AppendAllText(OutputhFilePath, line2);
         }
    
         File.WriteAllText(OutputhFilePath, sb.ToString());
         Console.ReadLine();
    

but what should I add so that the code does not replace the found lines to "date", but swap the first two characters of "xx.xx.xx" to the last two characters, for example: 29.06.20 to 20.06.29.

Thanks in advance!

4 Answers

You can Split('.'), then Reverse(), and Join('.') the result :

var sample = "29.06.20";

// using System.Linq --------------------------v--------v
var result = string.Join('.', sample.Split('.').Reverse());
    
Console.WriteLine(result); // outputs 20.06.29

Try it


If you prefer to stick with RegEx (which is preferred if you have something before or after the date), you can use capturing groups with parenthesis and then use $1, $2 and $3 as reference to the groups :

var sample = "29.06.20 look there is something after the date";
RegexOptions options = RegexOptions.None;
// Groups numbers             1       2         3
//                         v----v   v----v   v-----v
Regex regex1 = new Regex(@"(\d{2})\.(\d{2})\.(\d{2})", options);
var result = regex1.Replace(sample, "$3.$2.$1");
Console.WriteLine(result); // outputs 20.06.29 look there is something after the date

Try it

I would parse it to datetime:

        foreach (string line in lines)
        {
            DateTime date;
            if(DateTime.TryParse(line,out date)) 
                sb.AppendLine(date.ToString("yy.MM.dd"));
            else
                sb.AppendLine(line);
        }

If this is going to be date always, you can try using date time parsing,

 string first = "something like 29.06.20";
            RegexOptions options = RegexOptions.None;

            Regex regex1 = new Regex(@"\d{2}\.\d{2}\.\d{2}", options);

            string date = regex1.Match(first).Value;
            DateTime dt = DateTime.ParseExact(date, "dd.MM.yy", CultureInfo.InvariantCulture);
            dt.ToString("yy.mm.dd");

            string line2 = regex1.Replace(first, dt.ToString("yy.MM.dd"));

            Console.WriteLine(line2);

You can modify you suit your needs.

You can write a helper method like Fix() that can also be an extension method

string line2 = regex1.Replace(line, Fix(line));

private static string Fix(string line)
{
    // Extract the date
    RegexOptions options = RegexOptions.None;
    Regex regex1 = new Regex(@"\d{2}\.\d{2}\.\d{2}", options);
    string mydate = regex1.Matches(line)[0].ToString();
    var splitted = mydate.Split('.');
    if (splitted.Length == 3)
    {
        return splitted[2] + "." + splitted[1] + "." + splitted[0];
    }
    else
    {
        return "Error";
    }
}

The line:
"some text some text 29.06.20 some text some text"
will output:
some text some text 20.06.29 some text some text

Related