Home > database >  C# - Split a string separated by ':'
C# - Split a string separated by ':'

Time:08-25

Im trying to split this string:

PublishDate: "2011-03-18T11:08:07.983"

I tried Split method but it's not successful.

str.Split(new[] { ':', ' ' }, StringSplitOptions.RemoveEmptyEntries)

As a result I get PublishDate 2011-03-18T11 08 07.983

But correct result is PublishDate 2011-03-18T11:08:07.983

What i need to do?

CodePudding user response:

I would solve like this:

  • locate the index of the first :. The property name will be all the characters before this, which you can extract with Substring and Trim to remove whitespace before the colon, if present.
  • locate the index of the first " and last ". Characters between the first and last quotes are the property value.
string input = "PublishDate: \"2011-03-18T11:08:07.983\"";

int iColon = input.IndexOf(':');
int iOpenQuote = input.IndexOf('"', iColon);
int iCloseQuote = input.LastIndexOf('"');
string propertyName = input.Substring(0, iColon).Trim();
string propertyValue = input.Substring(iOpenQuote   1, iCloseQuote - iOpenQuote - 1);

This does not handle escaped characters within the property value (for example, to embed a literal quote or newline using a typical escape sequence like \" or \n). But it's likely good enough to extract a date/time string, and permits all characters because of the use of LastIndexOf. However, this is not robust against malformed input, so you will want to add checks for missing colon, or missing quote, or what happens when the close quote is missing (same same index for start and end quote).

CodePudding user response:

So if I got you right, you want as a result: PublishDate 2011-03-18T11:08:07.983.

Then I would recommend you to use the string.Replace method.

using System;

public class HelloWorld
{
    public static void Main(string[] args)
    {
        string yourData = "PublishDate: \"2011-03-18T11:08:07.983\"";
        
        // First replace the colon and the space after the PublishDate with and space
        // then replace the quotes from the timestamp -> "2011-03-18T11:08:07.983"
        yourData = yourData.Replace(": ", " ").Replace("\"", "");
        
        // Output the result -> PublishDate 2011-03-18T11:08:07.983
        Console.WriteLine(yourData);
    }
}

CodePudding user response:

Split(String, Int32, StringSplitOptions)

Splits a string into a maximum number of substrings based on a specified delimiting string and, optionally, options.

str.Split(':', 2,   StringSplitOptions.RemoveEmptyEntries)

https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=net-6.0#system-string-split(system-string-system-int32-system-stringsplitoptions)

  •  Tags:  
  • c#
  • Related