Efficiently split a string in format "{ {}, {}, ...}"

sql split string by delimiter
split(string java)
string split
sql split string by character
split string by length online
sql server split string by comma
sql split string into columns
how to divide a string into substrings in java

I have a string in the following format.

string instance = "{112,This is the first day 23/12/2009},{132,This is the second day 24/12/2009}"

private void parsestring(string input)
{
    string[] tokens = input.Split(','); // I thought this would split on the , seperating the {}
    foreach (string item in tokens)     // but that doesn't seem to be what it is doing
    {
       Console.WriteLine(item); 
    }
}

My desired output should be something like this below:

112,This is the first day 23/12/2009
132,This is the second day 24/12/2009

But currently, I get the one below:

{112
This is the first day 23/12/2009
{132
This is the second day 24/12/2009

I am very new to C# and any help would be appreciated.

Well, if you have a method that is called ParseString, it's a good thing it returns something (and it might not be that bad to say that it is ParseTokens instead). So if you do that, you can come to the following code

private static IEnumerable<string> ParseTokens(string input)
{
    return input
        // removes the leading {
        .TrimStart('{')
        // removes the trailing }
        .TrimEnd('}')
        // splits on the different token in the middle
        .Split( new string[] { "},{" }, StringSplitOptions.None );
}

The reason why it didn't work for you before, is because your understanding of how the split method works, was wrong, it will effectively split on all , in your example.

Now if you put this all together, you get something like in this dotnetfiddle

using System;
using System.Collections.Generic;

public class Program
{
    private static IEnumerable<string> ParseTokens(string input)
    {
        return input
            // removes the leading {
            .TrimStart('{')
            // removes the trailing }
            .TrimEnd('}')
            // splits on the different token in the middle
            .Split( new string[] { "},{" }, StringSplitOptions.None );
    }

    public static void Main()
    {
        var instance = "{112,This is the first day 23/12/2009},{132,This is the second day 24/12/2009}";
        foreach (var item in ParseTokens( instance ) ) {
            Console.WriteLine( item );
        }
    }
}

Java split String: How to split a String into tokens with , How do I split a string into number of substrings? How to split a string in C++? That is to say, how to get a collection of substrings representing the words of a sentence, or the pieces of data contained in a CSV entry? This is a simple question, but one which has multiple answers in C++. We will see 3 solutions, each one having advantages and drawbacks.

How to split a string based on a certain format using Regex?, How do you split a string by length in python? and use the regex split method. string[] tokens = Regex.Split(input, "(?<=}),"); Here, we use positive lookahead to split on a , which is immediately after a } (note: (?<= your string ) matches all the characters after your string only. you can read more about it here

Use Regex for this:

string[] tokens = Regex.Split(input, @"}\s*,\s*{")
  .Select(i => i.Replace("{", "").Replace("}", ""))
  .ToArray();

Pattern explanation:

\s* - match zero or more white space characters

Split a String, hey folks! i've been working on a process that performs a data entry function after However, it seems like there's a more efficient way of doing this by splitting  The following code splits a common phrase into an array of strings for each word. string phrase = "The quick brown fox jumps over the lazy dog."; string[] words = phrase.Split(' '); foreach (var word in words) { System.Console.WriteLine($"<{word}>"); } Every instance of a separator character produces a value in the returned array.

Add using System.Text.RegularExpressions; to top of the class

and use the regex split method

string[] tokens = Regex.Split(input, "(?<=}),");

Here, we use positive lookahead to split on a , which is immediately after a }

(note: (?<= your string ) matches all the characters after your string only. you can read more about it here

Java split string - Java tokenize string examples, If you want to split a string by a specific symbol, select the "Split by a Character" option and enter the split symbol below it (by default, What we effectively get is all occurrences of "x" replaced by "y". Format and align a multi-line string. Through the WHERE clause, we can filter the result set of the STRING_SPLIT function. In the following select statement, the WHERE clause will filter the result set of the function and will only return the row or rows which start with “le”. 1. 2.

If you dont want to your regular expressions, the following code will produce your required output.

        string instance = "{112,This is the first day 23/12/2009},{132,This is the second day 24/12/2009}";

        string[] tokens = instance.Replace("},{", "}{").Split('}', '{');
        foreach (string item in tokens)
        {
            if (string.IsNullOrWhiteSpace(item)) continue;

            Console.WriteLine(item);
        }

        Console.ReadLine();

LET US JAVA-3rd EDITION, Learn to split string into arraylist using single delimiter or multiple delimiters. In web applications, many times we have to pass data in CSV format or separated  parse (format_string) ¶ Loop over the format_string and return an iterable of tuples (literal_text, field_name, format_spec, conversion). This is used by vformat() to break the string into either literal text, or replacement fields. The values in the tuple conceptually represent a span of literal text followed by a single replacement field.

C# 7.0 All-in-One For Dummies, The format() method is a static method which builds a new string object using It enables us to search substrings within a large string efficiently. Splitting. Strings. While processing strings in Java applications, it is required to split a string in  Reference: folly/Format.h. Related. How to split a string in C++; How to find a substring in C++; How to replace all occurrences of a character in a std::string; How to do case-insensitive string comparison in C++; How to concatenate a string and an int in C++; How to convert a string to lower or upper case in C++; How to trim a std::string in C++

Split strings the right way - or the next best way, As usual, a little examination reveals a more efficient approach using our old friend Split(). Split(targets); // output will contain the eventual output information. string The String class also provides the Format() method for formatting output,​  When there is a need to split a string with the delimiter, the first function that comes to our mind usually is String.split(regex). However, it brings some serious performance issues, as it accepts a regex argument. Alternatively, we can use the StringTokenizer class to break the string into tokens. Another option is Guava's Splitter API.

Splitting a string using strtok() in C, He spent a lot of time fine-tuning this CLR function to efficiently parse a string. If you are currently using a CLR function and this is not it, I strongly  Excel has the capability to export a worksheet in Comma Separated Value (CSV) format. Let’s delve deeper into C# split string. Using the C# string Split() method allows you to extract the values from in between the commas. Similarly, the string Join()method will take individual values from an array and combine them with a separator, such as a

Comments
  • If the format is really that simple, split on "},{" for the separator, and then remove the orphan { from the first item in he result array, and the orphan } from the last item in the result array.
  • @SaniSinghHuttunen Could you help me?
  • you can use the TextFieldParser class even though its defined in the VisualBasic space. docs.microsoft.com/en-us/dotnet/api/… Also, if your inner text will not contain double quotes, then you can replace curly braces with double quotes, then use thhe text field parser to ignore the quotes
  • @EdPlunkett When I use the "},{" in the split method, I get error cannot convert to char from string. I am not sure what is wrong in it?
  • @Analia string[] tokens = input.Split("},{"); works for me.
  • Fair point on the efficiency, but I only wanted to make a more clear example, as I think the OP needs to start with the basics :) Nice solution, but why not yield, your solution seems to be perfect for it ;)
  • @Icepickle I thought about yield when I got to the end and avoided it for the same reason you quoted: I wanted to stick to the basics. yield return takes a bit to explain and is kind of janky until you get the hang of it!
  • Why not use lookahead, he only wants to split on , that come after a }
  • @AbishekAditya It doesn't make any difference :)
  • Thank you for the clear explaination
  • @Analia you can remove the { and } using a simple text replace after this