How to remove empty strings from c# array? - c#

I am removing values with less than 8 characters from an array, but empty strings still remain. How to get rid of them?
for (int i = 0; i < reportbOR.Length; i++)
{
border = "border:" +reportbOR[i].colorborder;
string[] text_arr = border.Split('\n');
foreach (var item in text_arr)
{
if (item.Length < 8)
border = border.Replace(item, "");
}
}

You could filter out null, white space, and character length with a couple of different approaches. We will start similar to your above code.
var border = new List<string>();
for(var index = 0; index < reportbOR.Length; index++)
if(!String.IsNullOrEmpty(reportbOR[index].colorBorder) && reportbOR[index].colorBorder.Length < 8)
border.Add($"border: {reportbOR[index].colorBorder}");
I won't mention the StringSplitOptions because of #NSevens response, the documentation is pretty self explanatory but could be applicable.
One thing to denote, if you use LINQ on a String it will parse into a character array. But if you use your root object you could leverage LINQ.
var borders = reportbOR
.Where(property => !String.IsNullOrEmpty(property.colorBorder) && property.colorBorder < 8))
.Select(property => new $"border: {property}");
Also, it would be important to know that if you only care about null or empty, then use IsNullOrEmpty. If you want to sanitize for white-space and white-space characters then use IsNullOrWhiteSpace.

You can use the overload of string.Split which accepts a StringSplitOptions enum:
string[] text_arr = border.Split(new string[] { "\n" },
StringSplitOptions.RemoveEmptyEntries);
Since it's unclear as to when you are having issues removing the empty entries, and you are also replacing strings with 8 or less characters with empty strings, you can use Linq:
text_arr = text_arr.Where(a => !string.IsNullOrWhitespace(a)).ToArray();
You can read about the overload here: stringsplitoptions
And here: string.split
EDIT Here it is in one line:
string[] text_arr = border.Split(new string[] { "\n" },
StringSplitOptions.RemoveEmptyEntries)
.Where(a => !string.IsNullOrWhitespace(a) && a.Length >= 8)
.ToArray();

Something like this?
for (int i = 0; i < reportbOR.Length; i++)
{
var strings = $"border:{reportbOR[i].colorborder}"
.Split(Environment.NewLine)
.Where(str => str.Length > 8);
border = string.Join(Environment.NewLine, strings);
}

try this
list = list.Where(s => !string.IsNullOrWhiteSpace(s)).ToList();

Related

Large Unicode List to Char[] c#

I pass a string containing separate characters on each line to a Unicode list with this code.
string MultiLineCharArray = string.Join(Environment.NewLine, CharArray);
var UnicodeList = MultiLineCharArray.Select(str => Convert.ToUInt16(str)).ToList();
when reversing it the program dies, it does not even try, very badly:
for (int i = 0; i < UnicodeList.Count; i++)
{
MultiLineCharArray = string.Join(Environment.NewLine, Convert.ToChar(UnicodeList[i]));
}
I need the MultiLineCharArray to then convert it into an Array of its valid Unicode characters (unicode = A) going through each line to convert it to a single string.
The Unicode list is very long (9,000) elements, maybe that's why the program crashed, is there a more optimal way to do it?
Use LINQ and String functions
// to populate charArray with dummy chars A through J
var charArray = Enumerable.Range(65, 10).Select(i => (char)i);
// your existing code
var multiLineCharArray = string.Join(Environment.NewLine, charArray);
var unicodeList = multiLineCharArray.Select(str => Convert.ToUInt16(str)).ToList();
// to reverse
var multiLineCharArray1 = new string(unicodeList.Select(u => (char)u).ToArray());
var charArray1 = multiLineCharArray1.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

Replace string if starts with string in List

I have a string that looks like this
s = "<Hello it´s me, <Hi how are you <hay"
and a List
List<string> ValidList= {Hello, hay} I need the result string to be like
string result = "<Hello it´s me, ?Hi how are you <hay"
So the result string will if it starts with an < and the rest bellogs to the list, keep it, otherwise if starts with < but doesn´t bellong to list replaces the H by ?
I tried using the IndexOf to find the position of the < and the if the string after starsWith any of the strings in the List leave it.
foreach (var vl in ValidList)
{
int nextLt = 0;
while ((nextLt = strAux.IndexOf('<', nextLt)) != -1)
{
//is element, leave it
if (!(strAux.Substring(nextLt + 1).StartsWith(vl)))
{
//its not, replace
strAux = string.Format(#"{0}?{1}", strAux.Substring(0, nextLt), strAux.Substring(nextLt + 1, strAux.Length - (nextLt + 1)));
}
nextLt++;
}
}
To give the solution I gave as a comment its proper answer:
Regex.Replace(s, string.Format("<(?!{0})", string.Join("|", ValidList)), "?")
This (obviously) uses regular expressions to replace the unwanted < characters by ?. In order to recognize those characters, we use a negative lookahead expression. For the example word list, this would look like this: (?!Hallo|hay). This will essentially match only if what we are matching is not followed by Hallo or hay. In this case, we are matching < so the full expression becomes <(?!Hallo|hay).
Now we just need to account for the dynamic ValidList by creating the regular expression on the fly. We use string.Format and string.Join there.
Something like this without using RegEx or LINQ
string s = "<Hello it´s me, <Hi how are you <hay";
List<string> ValidList = new List<string>() { "Hello", "hay" };
var arr = s.Split(new[] { '<' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < arr.Length; i++)
{
bool flag = false;
foreach (var item in ValidList)
{
if (arr[i].Contains(item))
{
flag = false;
break;
}
else
{
flag = (flag) ? flag : !flag;
}
}
if (flag)
arr[i] = "?" + arr[i];
else
arr[i] = "<" + arr[i];
}
Console.WriteLine(string.Concat(arr));
A possible solution using LINQ.It splits the string using < and checks if the "word" (text until a blank space found) following is in the Valid List,adding < or ? accordingly. Finally,it joins it all:
List<string> ValidList = new List<string>{ "Hello", "hay" };
string str = "<Hello it´s me, <Hi how are you <hay";
var res = String.Join("",str.Split(new char[] { '<' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => ValidList.Contains(x.Split(' ').First()) ? "<" + x : "?"+x));

Join List of strings trailing values don't require delimiters if the right most value is null

What im trying to achieve, but cant get my head around is if i have a list of strings say:
{"test","","data","","123","44"}
this should be joined by a character:
test::data::123:44
but if the list at the end is empty dont delimiter it
{"test","","data","","",""}
should be:
test::data
{"test","","","","",""}
should be:
test
{"test","","","","","44"}
should be:
test::::44
however the list can be of varying lengths which adds another level of complexity.
Just exclude the trailing empty elements from the list Count and then Join the remaining using Take:
List<string> input = ...;
int count = input.Count;
while (count > 0 && string.IsNullOrEmpty(input[count - 1]))
count--;
var output = string.Join(":", input.Take(count));
Using the List<T> specific FindLastIndex method, it can be reduced to the following "one liner":
var output = string.Join(":",
input.Take(input.FindLastIndex(s => !string.IsNullOrEmpty(s)) + 1));
First, with your array:
test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
where "test" is your array.
then:
string.Join("::", test);
EDIT:
If you're getting your array of strings by splitting another string, consider the following:
string[] strs = myString.split(someDelimeter, StringSplitOptions.RemoveEmptyEntries);
Start by identifying the last element you want, then slice your list and join as you normally would:
var lastElementIndex = strings.Select((s, index) => string.IsNullOrEmpty(s) ? -1 : index).Max();
var prefix = strings.Take(lastElementIndex + 1);
var result = string.Join(":", prefix);
var obj = {"test","","data","","123","44"};
var count = obj.Count;
for (var i = count - 1; i > -1; i--)
{
if (obj[i]==String.Empty) {
obj.RemoveAt(i);
}
else break;
}
var arr = obj.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries);
var output = arr.Join(":", arr);

Delimit string and put it in listbox

I have a string like:
one,one,one,one,two,two,two,two,three,three,three,three,four,four,four,four,...
and I'd like to delimit it after every fourth comma and store it into a list box, like this:
one,one,one,one,
two,two,two,two,
three,three,three,three,
four,four,four,four,
...
What should be appropriate way to do this? Should I supposed to use regex to somehow delimit this string?
Thanks
Linqless alternative;
int s = 0, n = 0, len = inputString.Length;
for (var i = 0; i < len; i++) {
if (inputString[i] == ',' && ++n % 4 == 0 || i == len - 1) {
aListBox.Items.Add(inputString.Substring(s, i - s + 1));
s = i + 1;
}
}
This LINQ breaks your input into individual strings by delimiting on the comma, then uses an index in the Select method to group four items together at a time, then finally joins those four items into a single string again.
var input = "one,one,one,one,two,two,two,two,three,three,three,three"; // and so on
var result = input.Split(',')
.Select((s, i) => new {s, i})
.GroupBy(pair => pair.i / 4)
.Select(grp => string.Join(",", grp.Select(pair => pair.s)) + ",");
The result is a collection of strings, where the first one (based on your input) is "one,one,one,one,", then the second is "two,two,two,two," and so on...
From there, it's just a matter of setting it as the DataSource, ItemsSource or similar, depending on what technology you're using.

Getting rid of null/empty string values in a C# array

I have a program where an array gets its data using string.Split(char[] delimiter).
(using ';' as delimiter.)
Some of the values, though, are null. I.e. the string has parts where there is no data so it does something like this:
1 ;2 ; ; 3;
This leads to my array having null values.
How do I get rid of them?
Try this:
yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);
You could use the Where linq extension method to only return the non-null or empty values.
string someString = "1;2;;3;";
IEnumerable<string> myResults = someString.Split(';').Where<string>(s => !string.IsNullOrEmpty(s));
public static string[] nullLessArray(string[] src)
{
Array.Sort(src);
Array.Reverse(src);
int index = Array.IndexOf(src, null);
string[] outputArray = new string[index];
for (int counter = 0; counter < index; counter++)
{
outputArray[counter] = src[counter];
}
return outputArray;
}
You should replace multiple adjacent semicolons with one semicolon before splitting the data.
This would replace two semicolons with one semicolon:
datastr = datastr.replace(";;",";");
But, if you have more than two semicolons together, regex would be better.
datastr = Regex.Replace(datastr, "([;][;]+)", ";");
words = poly[a].Split(charseparators, StringSplitOptions.RemoveEmptyEntries);
foreach (string word in words)
{
richTextBox1.Text += (d + 1)+ " " + word.Trim(',')+ "\r\n";
d++;
}
charseparators is a space

Categories