Split a string to get separate email IDs in the string [duplicate] - c#

This question already has answers here:
C#: splitting a string and not returning empty string
(7 answers)
Closed 2 years ago.
I have a string that contains email addresses like this :
string emailIDs = "xyz#gmail.com;abc#yahoo.com;frog#gmail.com;whyme#hotmail.com;"
I want to add these emails in List.
I tried splitting it at ';' but this creates an extra record in the list which causes a null exception.
I want to split and add this to my List without any extra record. Please let me know how can I achieve this in c#?
I am trying like this:
List<string> To = new List<string>(emailIDs.Cc.Split(new[] { ";" },StringSplitOptions.RemoveEmptyEntries));
Following is the result:
I am trying to remove this extra record at the end be cause Cc contains only two records:

Use StringSplitOptions.RemoveEmptyEntries to get rid of blank entries when splitting.
See documentation: https://learn.microsoft.com/en-us/dotnet/api/system.stringsplitoptions?view=netframework-4.8
Example:
var list = emailIDs.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries);
Edit:
I think that the string you posted "xyz#gmail.com;abc#yahoo.com;frog#gmail.com;whyme#hotmail.com;" does not match the actual string you are passing to String.Split() method. Looking closely at the end of email.Cc, it contains whitespace at the end, generating a non-empty but blank string that will not be removed by StringSplitOptions.RemoveEmptyEntries.
What about trimming that whitespace before?
var list = emailIDs.TrimEnd().Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
^^^^^^^^^

Related

How to split a string array using char as delimiter [duplicate]

This question already has answers here:
How to split a string by a specific character? [duplicate]
(6 answers)
Closed 10 months ago.
I want to add ' char as delimiter to my string array but I have error telling conversion string to char impossible.
I see this How to split a string by a specific character?
string ineedtosplitthis = "i want 'to' split this";
string[] splitTest = ineedtosplitthis.Split("'").ToString();
The issues is that you have the .ToString() after your statement.
Change it to this:
string ineedtosplitthis = "i want 'to' split this";
string[] splitTest = ineedtosplitthis.Split('\'');
The reason why this code doesn't work:
string[] splitTest = ineedtosplitthis.Split("'").ToString();
Is because you are converting it to a string via ToString();, while assigning it to a string[].
Split(); already returns a string[], so there is no need to convert it.
Hope this explanation helped :)

How to split a string by an empty string delimiter [duplicate]

This question already has answers here:
Best way to specify whitespace in a String.Split operation
(11 answers)
Closed 4 years ago.
In java,
String.split("");
is possible.
ex)
String[] str = "Hello world!".split("")
Like this, I want to split String without escape sequence.
But in C#, I tried it and IDE said 'Error'. Is there any solution?
edit)
Code:
String[] str = "Hello world!".split("");
the result is str[0] = H, str[1] = e, ...(in java)
In C#, I tried
strI[i] = "Hello World!".Split('');
And the result is
'error CS1011: Empty character literal
I want to split string with Empty literal.
Please note that no overloaded methods of String.Split() accepts a string as first argument like what you used. Following are the possible overloaded methods
The thing you are looking for is to split a string into characters. For that you can depend on String.ToCharArray Method, which will Copies the characters in this instance to a Unicode character array.:
char[] charArray = "Hello world!".ToCharArray();
So that we can access each characters using its index, that means - charArray[0] will be H.
If you need the splitted characters into a string array means you can use something like this:
string[] strArray = "Hello world!".Select(x=> x.ToString())
.ToArray();
The reason you are getting an error is because there is no method with the signature matching your call. In other words, when you call Split method, you must pass the first parameter as a character array or string array, whereas you are passing the first argument as simply a string.
Following call would not throw any error since it matches the signature of Split method.
string[] sArray = s.Split(new string[] {""}, StringSplitOptions.None);
However, above method will result in nothing productive since the resulting array will contain only one element whose value will be original string.
If your goal was to split a string into individual characters then you can use code like below.
string s = "some string";
var splitString = s.ToCharArray();

C#: Split comma-separated strings, but not if comma enclosed in single quotes [duplicate]

This question already has answers here:
split a comma-separated string with both quoted and unquoted strings [duplicate]
(16 answers)
Closed 5 years ago.
I am parsing a text file from some old hardware and I need to extract an array of strings from one long string.
Elements are comma-separated
Each individual string is enclosed in single quotes
'Hello', 'World'
{"'Hello', "'World'"}
Single quotes for any other reason are illegal and there is no escaping character equivalent; you cannot write the word "Bob's" nor can do something like "Bob\'s".
Ordinarily it would be easy to get the individual elements by splitting on the comma:
string testString = "'Hello', 'World'";
ArrayList result = new ArrayList(testString.Split(',');
But I can't do this; if a comma is in-between single quotes it is text, not a separator.
This is one element:
'Hello, World'
{"'Hello, World'"}
How can I extract the elements checking to see if the comma is in-between single quotes?
'Hello', 'World', 'Hello, World'
{"'Hello'", "'World'", "'Hello, World'"}
One more detail: I cannot guarantee the amount of whitespace between elements:
'Hello', 'World', 'Hello, World'
P.S. Here is the same question I asked for Swift: Swift: Split comma-separated strings, but not if comma enclosed in single quotes
You have not answered whether the strings can contain embedded single quotes & how they might be escaped.
If every string follows the pattern of [SingleQuote][Text][SingleQuote], here's a RegEx that will do what you need:
'[^']+'
If you have empty strings in the single quotes, use:
'[^']*'
The easiest way would be using Json deserialzer :
private string[] F(string input){
return Newtonsoft.Json.
JsonConvert.DeserializeObject("["+input+"]",typeof(string[]));
}
// now call F:
var result= F("'Hello','World','Hello,World'");
I tried this approach but I wonder if this works most of the time.
const string str = "'Hello', 'World', 'Hello, World'";
ArrayList arrStr = new ArrayList(str.Split('\''));
List<string> myString = new List<string>();
for (int i = 0 + 1; i < arrStr.Count; i+=2)
{
myString.Add(arrStr[i].ToString());
}
Also, i'm not sure if your string has contractions in it.

Trim space in <list>string C#

I am working on an application where I have multiple ID in a string that I passed from my view separated by a ';'.
So this is what it looks like "P171;P172".
if (ModelState.IsValid)
{
hiddenIDnumber= hiddenIDnumber.Trim();
List<string> listStrLineElements = hiddenIDnumber.Split(';').ToList();
foreach (string str in listStrLineElements)
The problem is, when I split my hiddenIDnumber, even if I have two numbers, I get a count of 3 and "" is returned (which I believe is an empty space).
When I use a breakpoint i get "P171","P172" AND "".
This is causing my program to fail because of my FK constraints.
Is there a way to "overcome this and somehow "trim" the space out?
Use another overload of string.Split whih allows you to ignore empty entries. For example:
List<string> listStrLineElements = hiddenIDnumber
.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
I would say that one way to do this would be to use String Split Options. With String.Split there is an overload that takes two arguments, i.e. it would be like
myString.Split(new [] {';'}, StringSplitOptions.RemoveEmptyEntries);
This should prevent any entries in your array that would only be an empty string.
var listStrLineElements = hiddenIDnumber.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries);
Use the parameter StringSplitOptions.RemoveEmptyEntries to automatically remove empty entries from the result list.
You can try:
IList<string> listStrLineElements = hiddenIDnumber.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
I prefer this over new [] { ';' } for readability, and return it to an interface (IList<string>).
You will end up with the number of ;s plus one when you split. Since your comment mentions you have 2 ;s, you will get 3 in your list: before the first semicolon, between the first and the second, and after the second. You are not getting an empty space, you are getting a string.Empty because you have nothing after the last ;
if (ModelState.IsValid)
{
hiddenIDnumber= hiddenIDnumber.Trim(";");
List<string> listStrLineElements = hiddenIDnumber.Split(';').ToList();
foreach (string str in listStrLineElements)
This way you get rid of the ; at the end before you split, and you don't get an empty string back.

Split string into elements of a string array [duplicate]

This question already has answers here:
How can I split a string with a string delimiter? [duplicate]
(7 answers)
Closed 8 years ago.
I've got a string with the format of:
blockh->127.0.0.1 testlocal.de->127.0.0.1 testlocal2.com
Now I need to seperate the elements, best way would be a string array I think. I would need to get only these elements seperated:
127.0.0.5 somerandompage.de
127.0.0.1 anotherrandompage.com
How to split and filter the array to get only these elements?
Using the .Filter() Methode doesn't to the job.
You can use the string Split method:
var st = "blockh->127.0.0.1 testlocal.de->127.0.0.1 testlocal2.com";
var result = st.Split(new [] { "->" }, StringSplitOptions.None);
You can achieve the same with a Regex:
var result = Regex.Split(st, "->");
As a note from #Chris both of these will split the string into an array with 3 elements:
blockh
127.0.0.1 testlocal.de
127.0.0.1 testlocal2.com
In case you want to get rid of blockh, you can do a regex match using an IP address and domain regex:
var ip = new Regex(#"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b\s*(([\w][\w\-\.]*)\.)?([\w][\w\-]+)(\.([\w][\w\.]*))");
var result = ip.Matches(st).Cast<Match>()
.Select(m => m.Value)
.ToArray();
This will get only the two elements containing IP addresses.
You can use a string Split() method to do that.
var s = "testlocal->testlocal2";
var splitted = s.Split(new[] {"->"}, StringSplitOptions.RemoveEmptyEntries); //result splitted[0]=testlocal, splitted[1]=testlocal2
If the simpler versions for splitting a string don't work for you, you will likely be served best by defining a Regular Expression and extracting matches.
That is described in detail in this MSDN article: http://msdn.microsoft.com/en-us/library/ms228595.aspx
For more information on how Regular Expressions can look this page is very helpful: http://regexone.com/

Categories