Asked  7 Months ago    Answers:  5   Viewed   33 times

I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a newline, so what is the best way to do it?

 Answers

68

To split on a string you need to use the overload that takes an array of strings:

string[] lines = theText.Split(
    new[] { Environment.NewLine },
    StringSplitOptions.None
);

Edit:
If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text:

string[] lines = theText.Split(
    new[] { "rn", "r", "n" },
    StringSplitOptions.None
);
Tuesday, June 1, 2021
 
StampyCode
answered 7 Months ago
30

In order to split by a string you'll have to use the string array overload.

string data = "THExxQUICKxxBROWNxxFOX";

return data.Split(new string[] { "xx" }, StringSplitOptions.None);
Tuesday, June 1, 2021
 
aslum
answered 7 Months ago
39

As always you start with a model:

public class MyViewModel
{
    public int? Year { get; set; }
    public int? Month { get; set; }

    public IEnumerable<SelectListItem> Years
    {
        get
        {
            return Enumerable.Range(2000, 12).Select(x => new SelectListItem
            {
                Value = x.ToString(),
                Text = x.ToString()
            });
        }
    }
}

then a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    public ActionResult Months(int year)
    {
        if (year == 2011)
        {
            return Json(
                Enumerable.Range(1, 3).Select(x => new { value = x, text = x }), 
                JsonRequestBehavior.AllowGet
            );
        }
        return Json(
            Enumerable.Range(1, 12).Select(x => new { value = x, text = x }),
            JsonRequestBehavior.AllowGet
        );
    }
}

and finally a view:

@model AppName.Models.MyViewModel

@Html.DropDownListFor(
    x => x.Year, 
    new SelectList(Model.Years, "Value", "Text"),
    "-- select year --"
)

@Html.DropDownListFor(
    x => x.Month, 
    Enumerable.Empty<SelectListItem>(),
    "-- select month --"
)

<script type="text/javascript">
    $('#Year').change(function () {
        var selectedYear = $(this).val();
        if (selectedYear != null && selectedYear != '') {
            $.getJSON('@Url.Action("Months")', { year: selectedYear }, function (months) {
                var monthsSelect = $('#Month');
                monthsSelect.empty();
                $.each(months, function (index, month) {
                    monthsSelect.append($('<option/>', {
                        value: month.value,
                        text: month.text
                    }));
                });
            });
        }
    });
</script>

Obviously you will notice that in my example I have hardcoded all the values. You should improve this logic by using notions like current year, current month, probably even fetch those values from a repository, etc... but for the purpose of the demonstration this should be enough to put you on the right track.

Tuesday, June 1, 2021
 
Teno
answered 7 Months ago
50

Use string.Split(char [])

string strings = "4,6,8n9,4";
string [] split = strings .Split(new Char [] {',' , 'n' });

EDIT

Try following if you get any unnecessary empty items. String.Split Method (String[], StringSplitOptions)

string [] split = strings .Split(new Char [] {',' , 'n' }, 
                                 StringSplitOptions.RemoveEmptyEntries);

EDIT2

This works for your updated question. Add all the necessary split characters to the char [].

string [] split = strings.Split(new Char[] { ',', '\', 'n' },
                                 StringSplitOptions.RemoveEmptyEntries);
Thursday, June 24, 2021
 
sunshinejr
answered 6 Months ago
11

| is a special symbol in regular expression. Use \| instead.

I'll explain why I appended 2 slashes. To escape the |, I need |. However, to represent the string |, "\|" is required because itself needs to be escaped in a string lateral.

And, as xagyg has pointed out in the comment, split will treat the parameter as a regular expression. It will not be treated as a plain string.

In this use case, you may be interested to learn about Pattern.quote. You can do Pattern.quote("|"). This way, none of the characters will be treated as special ones.

Tuesday, August 24, 2021
 
Elijah W. Gagne
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share