I have a string,
string aString = "a,aaa,aaaa,aaaaa,,,,,";
Where i want to insert to a List..But when i do using the following method,
List<string> aList = new List<string>();
aList.AddRange(aString.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
MessageBox.Show(aList.Count.ToString());
I get the count as only 4, But there are actually 8 elements even the final characters in between the (,) sign is blank.
But if i pass the string as shown below,
string aString = "a,aaa,aaaa,aaaaa, , , , ,";
It will be shown as 8 elements..Please help me on this, the default way thw program retrieves the string is like so,
a,aaa,aaaa,aaaaa,,,,,
Please help on this one, It would be great if i could add spaces to the empty area or any other way so that i could add all these characters in between (,) sign to the list.. even the blank areas. Thank you :)
Don't use StringSplitOptions.RemoveEmptyEntries
string aString = "a,aaa,aaaa,aaaaa,,,,,";
var newStr = String.Join(", ", aString.Split(','));
I think you must remove StringSplitOptions.RemoveEmptyEntries
aList.AddRange(aString.Replace(",,", ", ,").Split(new string[] { "," }));
You can just Replace the space before split it.
aList.AddRange(aString.Replace(" ", "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
Related
I'm currently replacing a very old (and long) C# string parsing class that I think could be condensed into a single regex statement. Being a newbie to Regex, I'm having some issues getting it working correctly.
Description of the possible input strings:
The input string can have up to three words separated by spaces. It can stop there, or it can have an = followed by more words (any amount) separated by a comma. The words can also be contained in quotes. If a word is in quotes and has a space, it should NOT be split by the space.
Examples of input and expected output elements in the string array:
Input1:
this is test
Output1:
{"this", "is", "test"}
Input2:this is test=param1,param2,param3
Output2: {"this", "is", "test", "param1", "param2", "param3"}
Input3:use file "c:\test file.txt"=param1 , param2,param3
Output3: {"use", "file", "c:\test file.txt", "param1", "param2", "param3"}
Input4:log off
Output4: {"log", "off"}
And the most complex one:
Input5:
use object "c:\test file.txt"="C:\Users\layer.shp" | ( object = 10 ),param2
Output5:
{"use", "object", "c:\test file.txt", "C:\Users\layer.shp | ( object = 10 )", "param2"}
So to break this down:
I need to split by spaces up to the first three words
Then, if there is an =, ignore the = and split by commas instead.
If there are quotes around one of the first three words and contains a space, INCLUDE that space (don't split)
Here's the closest regex I've got:
\w+|"[\w\s\:\\\.]*"+([^,]+)
This seems to split the string based on spaces, and by commas after the =. However, it seems to include the = for some reason if one of the first three words is surrounded by quotes. Also, I'm not sure how to split by space only up to the first three words in the string, and the rest by comma if there is an =.
It looks like part of my solution is to use quantifiers with {}, but I've unable to set it up properly.
Without Regex. Regex should be used when string methods cannot be used. :
string[] inputs = {
"this is test",
"this is test=param1,param2,param3",
"use file \"c:\\test file.txt\"=param1 , param2,param3",
"log off",
"use object \"c:\\test file.txt\"=\"C:\\Users\\layer.shp\" | ( object = 10 ),param2"
};
foreach (string input in inputs)
{
List<string> splitArray;
if (!input.Contains("="))
{
splitArray = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
else
{
int equalPosition = input.IndexOf("=");
splitArray = input.Substring(0, equalPosition).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
string end = input.Substring(equalPosition + 1);
splitArray.AddRange(end.Split(new char[] { ',' }).ToList());
}
string output = string.Join(",", splitArray.Select(x => x.Contains("\"") ? x : "\"" + x + "\""));
Console.WriteLine(output);
}
Console.ReadLine();
I'm trying to split a string that can come in with either commas or newlines, based on an input from a textarea. I'm not sure of the syntax to split this string in c#.
Currently I have:
string[] splitString = inputString.Split(','); //WORKS
//string[] splitString = inputString.Split(new string[] { ",","\r\n","\n" }, StringSplitOptions.None); //DOES NOT WORK
Since some text uses \r for new line.
You should use the code below and remove the empty entries to make the array cleaner.
string[] splitString = inputString.Split(new string[] { ",", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
or using Regex.Split. (This doesn't remove empty entries.)
String[] splitString = Regex.Split(inputString, "[,\r\n]");
Update
You can also use Regex.Split with empty entries removed, thanks to WiktorStribiżew's comment.
The code below removes the empty entries which aren't in the beginning or end of the string.
String[] splitString = Regex.Split(inputString, "[,\r\n]+");
To eliminate empty entries showing in the beginning or end of the line, use the code below.
Regex.Split(Regex.Replace(inputString, "^[,\r\n]+|[,\r\n]+$", ""), "[,\r\n]+");
Regular Expression Language
If you want more informations about Regex, or how it works, you can look here for a quick reference.
You can pass Environment.NewLine into your string array:
string[] splitString = inputString.Split(new string[] { ",", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
Trim() Function Not Working Please Help its not trimming the white space.
string samplestring = "172-6573-4955";
string[] array = samplestring .Split('-');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));
array[1] = restOfArray.Trim(); // providing value "6573 4955"
The scenario is I am splitting string and merging 2nd and last index into one but it's merging with white spaces.
Trim() removes whitespace from the front and back of a string, not in the middle. The whitespaces in the middle are being inserted by the " " provided as the parameter to Join() method. You could provide string.empty instead.
Trim is used to remove all leading and trailing white-space. And you want to trim the white space from middle. You may try like this:
string restOfArray = string.Join("", array.Skip(1));
or better:
string restOfArray = string.Join(string.Empty, array.Skip(1));
instead of
string restOfArray = string.Join(" ", array.Skip(1));
Trim is working as expected. Taken from String.Trim Method:
Removes all leading and trailing white-space characters from the
current String object.
The possible solutions for you are :
string restOfArray = string.Join(string.Empty, array.Skip(1));
Or
array[1] = restOfArray.Replace(" ", string.Empty).Trim();
To just split the first n-let from the rest use an additional array or you will end up with spurious data. And join with the correct separator you used in split(-):
string restOfArray = string.Join("-", array.Skip(1));
string[] result = new string[] { firstElem, restOfArray };
You don't need Trim().
You can simplify your code this way:
string[] splitCode(string code)
{
string[] segments;
segments = code.Split('-');
return new string[] { segments.First(), string.Join("-", segments.Skip(1)) };
}
Trim really isn't need here; you can simply split the string and join the parts you want:
string source = "172-6573-4955";
string[] splitter = new string[] {"-"};
string[] result;
result = source.Split(splitter, StringSplitOptions.None);
string final = (result[1] + result[2]);
Console.Write(final);
Result:
65734955
Try this:
string samplestring = "172-6573-4955";
string[] array = samplestring.Split(new char[] {'-'},2);
string result = array[1].Replace("-","");
Also, for your question about randomly putting spaces, can u pls explain "randomly" here.
I may have just hit the point where i;m overthinking it, but I'm wondering: is there a way to designate a list of special characters that should all be considered delimiters, then splitting a string using that list? Example:
"battlestar.galactica-season 1"
should be returned as
battlestar galactica season 1
i'm thinking regex but i'm kinda flustered at the moment, been staring at it for too long.
EDIT:
Thanks guys for confirming my suspicion that i was overthinking it lol: here is what i ended up with:
//remove the delimiter
string[] tempString = fileTitle.Split(#"\/.-<>".ToCharArray());
fileTitle = "";
foreach (string part in tempString)
{
fileTitle += part + " ";
}
return fileTitle;
I suppose i could just replace delimiters with " " spaces as well... i will select an answer as soon as the timer is up!
The built-in String.Split method can take a collection of characters as delimiters.
string s = "battlestar.galactica-season 1";
string[] words = s.split('.', '-');
The standard split method does that for you. It takes an array of characters:
public string[] Split(
params char[] separator
)
You can just call an overload of split:
myString.Split(new char[] { '.', '-', ' ' }, StringSplitOptions.RemoveEmptyEntries);
The char array is a list of delimiters to split on.
"battlestar.galactica-season 1".Split(new string[] { ".", "-" }, StringSplitOptions.RemoveEmptyEntries);
This may not be complete but something like this.
string value = "battlestar.galactica-season 1"
char[] delimiters = new char[] { '\r', '\n', '.', '-' };
string[] parts = value.Split(delimiters,
StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
Console.WriteLine(parts[i]);
}
Are you trying to split the string (make multiple strings) or do you just want to replace the special characters with a space as your example might also suggest (make 1 altered string).
For the first option just see the other answers :)
If you want to replace you could use
string title = "battlestar.galactica-season 1".Replace('.', ' ').Replace('-', ' ');
For more information split with easy examples you may see following Url:
This also include split on words (multiple chars).
C# Split Function explained
I'm trying to split a song title into two strings- the artist and song.
I receive the original string like this: "artist - song".
Using this code, I split the string using '-' as the spliiter:
char[] splitter = { '-' };
string[] songInfo = new string[2];
songInfo = winAmp.Split(splitter);
This works fine and all, except when I get to a band with '-' in the name, like SR-71.
However, since the original strings are separated with a space then a - and a space again (like SR-71 - Tomorrow), how would I split the string so this happens? I tried changing splitter to a string and inputting
string[] splitter = { " - " };
in it, but it returns that there is no overload match.
For some reason, string.Split has no overload that only takes a string array.
You need to call this overload:
string[] songInfo = winAmp.Split(new string[] { " - " }, StringSplitOptions.None);
Don't ask me why.
You can also use
Match M = System.Text.RegularExpressions.Regex.match(str,"(.*?)\s-\s(.*)");
string Group = M.Groups[1].Value;
string Song = M.Groups[2].Value;