Deleting all empty elements from the end of a string array [duplicate] - c#

I want to remove empty and null string in the split operation:
string number = "9811456789, ";
List<string> mobileNos = number.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(mobile => mobile.Trim()).ToList();
I tried this but this is not removing the empty space entry

var mobileNos = number.Replace(" ", "")
.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();

As I understand it can help to you;
string number = "9811456789, ";
List<string> mobileNos = number.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
the result only one element in list as [0] = "9811456789".
Hope it helps to you.

a string extension can do this in neat way as below
the extension :
public static IEnumerable<string> SplitAndTrim(this string value, params char[] separators)
{
Ensure.Argument.NotNull(value, "source");
return value.Trim().Split(separators, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim());
}
then you can use it with any string as below
char[] separator = { ' ', '-' };
var mobileNos = number.SplitAndTrim(separator);

I know it's an old question, but the following works just fine:
string number = "9811456789, ";
List<string> mobileNos = number.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
No need for extension methods or whatsoever.

"string,,,,string2".Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return ["string"],["string2"]

The easiest and best solution is to use both StringSplitOptions.TrimEntries to trim the results and StringSplitOptions.RemoveEmptyEntries to remove empty entries, fed in through the pipe operator (|).
string number = "9811456789, ";
List<string> mobileNos = number
.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
.ToList();
Checkout the below test results to compare how each option works,

Related

Extract contents between specific tags in a textfile - C#

I have a text file with the following information:
ALLOC
apple1
orange1
banana1
ALLOC
apple2
orange2
banana2
ALLOC
apple3
orange3
banana3
Based on the help from stackflow community, I am now able to read the whole file.I also found out that to extract contents between a tag, for ex, ALLOC, I could write:
var filelocation = #"c:\Fruits.txt";
var sectionLines = File.ReadAllLines(filelocation).TakeWhile(l => !l.StartsWith("ALLOC"));
But this will give me IEnumerable<string>:
apple1
orange1
banana1
apple2
orange2
banana2
apple3
orange3
How do I create 3 separate strings as
string1 = apple1 orange1 banana1
string2 = apple2 ornage2 banana2
string3 = apple3 orange3
In short, need to extract contents between tags.
Here is some approach how you can return result which you want:
string[] words = { "ALLOC", "apple1", "orange1", "banana1", "ALLOC", "apple2", "orange2", "banana2", "ALLOC" };
var result = string.Join(" ", words)
.Split(new string[] { "ALLOC" }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Trim(' '));
First I am making single string of all words. Than I am splitting by "ALLOC", and selecting trimmed strings.
Result is:
string[] result = { "apple1 orange1 banana1", "apple2 orange2 banana2" };
For your case,
var filelocation = #"c:\Fruits.txt";
var allLines = File.ReadAllLines(filelocation);
var sectionLines = string.Join(" ", allLines)
.Split(new string[] { "ALLOC" }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Trim(' '));
This might do the trick for you
string fullstr = File.ReadAllText("c:\\Fruits.txt");
string[] parts = fullstr.Split(new string[] { "ALLOC" }, StringSplitOptions.RemoveEmptyEntries);
List<string> outputstr = new List<string>();
foreach(string p in parts)
{
outputstr.Add(p.Replace("\r\n", " ").Trim(' '));
}
Here we read all text at once using File.ReadAllText and then splitted it with ALLOC and then in the outputstr just added the splitted string by replacing \r\n that is new line with a space and trimmed the result.

How do I efficiently split the values from a text file into my program?

I have a text file where I have to split the values with every space (' ') and newline('\n'). It does not work very well since every newline has a carriage return connected to it (\r\n).
char[] param = new char[] {' ','\n','\r'}; // The issue
string[] input = fill.Split(param);
The param array does not accept a '\r\n' parameter as n split argument, that is why I used '\n' and '\r' separately, but it does not work the way it needs to work. Any suggestions?
Use the overload of String.Split() that takes an array of strings instead of the overload that takes an array of chars.
string[] result = text.Split(new string[] { " ", Environment.NewLine },
StringSplitOptions.None);
string fill = #"one two three four";
string[] result = fill.Split(new string[] { " ", Environment.NewLine },
StringSplitOptions.None);
foreach (var s in result)
{
Console.WriteLine(s);
}
Here is a DEMO.
But remember, Environment.NewLine is
A string containing "\r\n" for non-Unix platforms, or a string
containing "\n" for Unix platforms.
There is an overload that accepts strings:
string[] input = fill.Split(
new string[] { " ", Environment.NewLine },
StringSplitOptions.None);
You can also use Environment.NewLine instead of "\r\n".
But if you want to support all kinds of line-endings, you better specify all the popular possiblities:
string[] input = fill.Split(
new string[] { " ", "\n", "\r\n" },
StringSplitOptions.None);

how would you remove the blank entry from array

How would you remove the blank item from the array?
Iterate and assign non-blank items to new array?
String test = "John, Jane";
//Without using the test.Replace(" ", "");
String[] toList = test.Split(',', ' ', ';');
Use the overload of string.Split that takes a StringSplitOptions:
String[] toList = test.Split(new []{',', ' ', ';'}, StringSplitOptions.RemoveEmptyEntries);
You would use the overload of string.Split which allows the suppression of empty items:
String test = "John, Jane";
String[] toList = test.Split(new char[] { ',', ' ', ';' },
StringSplitOptions.RemoveEmptyEntries);
Or even better, you wouldn't create a new array each time:
private static readonly char[] Delimiters = { ',', ' ', ';' };
// Alternatively, if you find it more readable...
// private static readonly char[] Delimiters = ", ;".ToCharArray();
...
String[] toList = test.Split(Delimiters, StringSplitOptions.RemoveEmptyEntries);
Split doesn't modify the list, so that should be fine.
string[] result = toList.Where(c => c != ' ').ToArray();
Try this out using a little LINQ:
var n = Array.FindAll(test, str => str.Trim() != string.Empty);
You can put them in a list then call the toArray method of the list, or with LINQ you could probably just select the non blank and do toArray.
If the separator is followed by a space, you can just include it in the separator:
String[] toList = test.Split(
new string[] { ", ", "; " },
StringSplitOptions.None
);
If the separator also occurs without the trailing space, you can include those too:
String[] toList = test.Split(
new string[] { ", ", "; ", ",", ";" },
StringSplitOptions.None
);
Note: If the string contains truely empty items, they will be preserved. I.e. "Dirk, , Arthur" will not give the same result as "Dirk, Arthur".
string[] toList = test.Split(',', ' ', ';').Where(v => !string.IsNullOrEmpty(v.Trim())).ToArray();

What is the best way to convert a string separated by return chars into a List<string>?

I need to often convert a "string block" (a string containing return characters, e.g. from a file or a TextBox) into List<string>.
What is a more elegant way of doing it than the ConvertBlockToLines method below?
using System;
using System.Collections.Generic;
using System.Linq;
namespace TestConvert9922
{
class Program
{
static void Main(string[] args)
{
string testBlock = "line one" + Environment.NewLine +
"line two" + Environment.NewLine +
"line three" + Environment.NewLine +
"line four" + Environment.NewLine +
"line five";
List<string> lines = StringHelpers.ConvertBlockToLines(testBlock);
lines.ForEach(l => Console.WriteLine(l));
Console.ReadLine();
}
}
public static class StringHelpers
{
public static List<string> ConvertBlockToLines(this string block)
{
string fixedBlock = block.Replace(Environment.NewLine, "§");
List<string> lines = fixedBlock.Split('§').ToList<string>();
lines.ForEach(s => s = s.Trim());
return lines;
}
}
}
List<string> newStr = str.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
This will keep consecutive newlines as empty strings (see StringSplitOptions)
No need to convert to your special sign:
List<string> strings = str.Split(new string[] {Environment.NewLine}, StringSplitOptions.None).ToList();
strings.ForEach(s => s = s.Trim());
Have you tried splitting on newline/carriage return and using the IEnumerable ToList extension?
testBlock.Split( new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries )
.ToList()
If you want to keep empty lines but may have both linefeed and carriage return.
textBlock.Replace( "\r\n", "\n" ).Replace( "\r", "\n" ).Split( '\n' ).ToList();
Hmm. You know that string now has a .Split() that takes a string[] array, right?
So ...
string[] lines = data.Split(
new string[1]{ Environment.NewLine },
StringSplitOptions.None
);
ou can use RegEx.Split to split directly using the Enviroment.NewLine.
public static List<string> ConvertBlockToLines(this string block)
{
return Regex.Split(block, Environment.NewLine).ToList();
}
LINQ!
var linesEnum = testBlock.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).AsEnumerable();
List<string> lines = linesEnum.ToList();

How do I split a string into an array?

I want to split a string into an array. The string is as follows:
:hello:mr.zoghal:
I would like to split it as follows:
hello mr.zoghal
I tried ...
string[] split = string.Split(new Char[] {':'});
and now I want to have:
string something = hello ;
string something1 = mr.zoghal;
How can I accomplish this?
String myString = ":hello:mr.zoghal:";
string[] split = myString.Split(':');
string newString = string.Empty;
foreach(String s in split) {
newString += "something = " + s + "; ";
}
Your output would be:
something = hello; something = mr.zoghal;
For your original request:
string myString = ":hello:mr.zoghal:";
string[] split = myString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
var somethings = split.Select(s => String.Format("something = {0};", s));
Console.WriteLine(String.Join("\n", somethings.ToArray()));
This will produce
something = hello;
something = mr.zoghal;
in accordance to your request.
Also, the line
string[] split = string.Split(new Char[] {':'});
is not legal C#. String.Split is an instance-level method whereas your current code is either trying to invoke Split on an instance named string (not legal as "string" is a reserved keyword) or is trying to invoke a static method named Split on the class String (there is no such method).
Edit: It isn't exactly clear what you are asking. But I think that this will give you what you want:
string myString = ":hello:mr.zoghal:";
string[] split = myString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
string something = split[0];
string something1 = split[1];
Now you will have
something == "hello"
and
something1 == "mr.zoghal"
both evaluate as true. Is this what you are looking for?
It is much easier than that. There is already an option.
string mystring = ":hello:mr.zoghal:";
string[] split = mystring.Split(new char[] {':'}, StringSplitOptions.RemoveEmptyEntries);

Categories

Resources