How to split string that delimiters remain in the end of result? - c#

I have several delimiters. For example {del1, del2, del3 }.
Suppose I have text : Text1 del1 text2 del2 text3 del3
I want to split string in such way:
Text1 del1
text2 del2
text3 del3
I need to get array of strings, when every element of array is texti deli.
How can I do this in C# ?

String.Split allows multiple split-delimeters. I don't know if that fits your question though.
Example :
String text = "Test;Test1:Test2#Test3";
var split = text.Split(';', ':', '#');
//split contains an array of "Test", "Test1", "Test2", "Test3"
Edit: you can use a regex to keep the delimeters.
String text = "Test;Test1:Test2#Test3";
var split = Regex.Split(text, #"(?<=[;:#])");
// contains "Test;", "Test1:", "Test2#","Test3"

This should do the trick:
const string input = "text1-text2;text3-text4-text5;text6--";
const string matcher= "(-|;)";
string[] substrings = Regex.Split(input, matcher);
StringBuilder builder = new StringBuilder();
foreach (string entry in substrings)
{
builder.Append(entry);
}
Console.Out.WriteLine(builder.ToString());
note that you will receive empty strings in your substring array for the matches for the two '-';s at the end, you can choose to ignore or do what you like with those values.

You could use a regex. For a string like this "text1;text2|text3^" you could use this:
(.*;|.*\||.*\^)
Just add more alternative pattens for each delimiter.

If you want to keep the delimiter when splitting the string you can use the following:
string[] delimiters = { "del1", "del2", "del3" };
string input = "text1del1text2del2text3del3";
string[] parts = input.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for(int index = 0; index < parts.Length; index++)
{
string part = parts[index];
string temp = input.Substring(input.IndexOf(part) + part.Length);
foreach (string delimter in delimiters)
{
if ( temp.IndexOf(delimter) == 0)
{
parts[index] += delimter;
break;
}
}
}
parts will then be:
[0] "text1del1"
[1] "text2del2"
[2] "text3del3"

As #Matt Burland suggested, use Regex
List<string> values = new List<string>();
string s = "abc123;def456-hijk,";
Regex r = new Regex(#"(.*;|.*-|.*,)");
foreach(Match m in r.Matches(s))
values.Add(m.Value);

Related

Replace string with another string at a specified index

I trying to replace some part of a string in C#.
E.g. I have a string formatted like this:
"We $1 what we $2"
(with $1 and $2 are the 2 indexes that have to be replaced).
And a string array:
new string[] { "know", "do" };
So how do I replace the "$1" with "know", and the "$2" with "do"?
string replaceList = new string[] { "know", "do" };
string Str = "We $1 what we $2";
for(int i = 1; i <= replaceList; i++){
Str = Str.Replace("$" + i.ToString(), replaceList[i-1]);
}
if can use something like this :
string[] replaceList = new string[] { "know", "do" };
string str = string.Format("We {0} what we {1}", replaceList);
It will replace the {} pattern by the value of the array.

Separating string on each character and putting it in an array

I'm pulling a string from a MySQL database containing all ID's from friends in this format:
5+6+12+33+1+9+
Now, whenever i have to add a friend it's simple, I just take the the string and add whatever ID and a "+". My problem lies with separating all the ID's and putting it in an array. I'm currently using this method
string InputString = "5+6+12+33+1+9+";
string CurrentID = string.Empty;
List<string> AllIDs = new List<string>();
for (int i = 0; i < InputString.Length; i++)
{
if (InputString.Substring(i,1) != "+")
{
CurrentID += InputString.Substring(i, 1);
}
else
{
AllIDs.Add(CurrentID);
CurrentID = string.Empty;
}
}
string[] SeparatedIDs = AllIDs.ToArray();
Even though this does work it just seems overly complicated for what i'm trying to do.
Is there an easier way to split strings or cleaner ?
Try this:-
var result = InputString.Split(new char[] { '+' });
You can use other overloads of Split
as well if you want to remove empty spaces.
You should to use the Split method with StringSplitOptions.RemoveEmptyEntries. RemoveEmptyEntries helps you to avoid empty string as the last array element.
Example:
char[] delimeters = new[] { '+' };
string InputString = "5+6+12+33+1+9+";
string[] SeparatedIDs = InputString.Split(delimeters,
StringSplitOptions.RemoveEmptyEntries);
foreach (string SeparatedID in SeparatedIDs)
Console.WriteLine(SeparatedID);
string[] IDs = InputString.Split('+'); will split your InputString into an array of strings using the + character
var result = InputString.Split('+', StringSplitOptions.RemoveEmptyEntries);
extra options needed since there is a trailing +

C# How to get Words From String

Hi guys i was trying a lot to retrieve some other strings from one main string.
string src = "A~B~C~D";
How can i retrieve separately the letters? Like:
string a = "A";
string b = "B";
string c = "C";
string d = "D";
you could use Split(char c) that will give you back an array of sub strings seperated by the ~ symbol.
string src = "A~B~C~D";
string [] splits = src.Split('~');
obviously though, unless you know the length of your string/words in advance you won't be able to arbitrarily put them in their own variables. but if you knew it was always 4 words, you could then do
string a = splits[0];
string b = splits[1];
string c = splits[2];
string d = splits[3];
Try this one. It will split your string with all non-alphanumeric characters.
string s = "A~B~C~D";
string[] strings = Regex.Split(s, #"\W|_");
Please try this
string src = "A~B~C~D"
//
// Split string on spaces.
// ... This will separate all the words.
//
string[] words = src .Split('~');
foreach (string word in words)
{
Console.WriteLine(word);
}
You can do:
string src = "A~B~C~D";
string[] strArray = src.Split('~');
string a = strArray[0];
string b = strArray[1];
string c = strArray[2];
string d = strArray[3];
string src = "A~B~C~D";
string[] letters = src.Split('~');
foreach (string s in letters)
{
//loop through array here...
}
Consider...
string src = "A~B~C~D";
string[] srcList = src.Split(new char[] { '~' });
string a = srcList[0];
string b = srcList[1];
string c = srcList[2];
string d = srcList[3];
string words[]=Regex.Matches(input,#"\w+")
.Cast<Match>()
.Select(x=>x.Value)
.ToArray();
\w matches a single word i.e A-Z or a-z or _ or a digit
+is a quantifier which matches preceding char 1 to many times
I like to do it this way:
List<char> c_list = new List<char>();
string src = "A~B~C~D";
char [] c = src.ToCharArray();
foreach (char cc in c)
{
if (cc != '~')
c_list.Add(cc);
}

Replace placeholders in order

I have a part of a URL like this:
/home/{value1}/something/{anotherValue}
Now i want to replace all between the brackets with values from a string-array.
I tried this RegEx pattern: \{[a-zA-Z_]\} but it doesn't work.
Later (in C#) I want to replace the first match with the first value of the array, second with the second.
Update: The /'s cant be used to separate. Only the placeholders {...} should be replaced.
Example: /home/before{value1}/and/{anotherValue}
String array: {"Tag", "1"}
Result: /home/beforeTag/and/1
I hoped it could works like this:
string input = #"/home/before{value1}/and/{anotherValue}";
string pattern = #"\{[a-zA-Z_]\}";
string[] values = {"Tag", "1"};
MatchCollection mc = Regex.Match(input, pattern);
for(int i, ...)
{
mc.Replace(values[i];
}
string result = mc.GetResult;
Edit:
Thank you Devendra D. Chavan and ipr101,
both solutions are greate!
You can try this code fragment,
// Begin with '{' followed by any number of word like characters and then end with '}'
var pattern = #"{\w*}";
var regex = new Regex(pattern);
var replacementArray = new [] {"abc", "cde", "def"};
var sourceString = #"/home/{value1}/something/{anotherValue}";
var matchCollection = regex.Matches(sourceString);
for (int i = 0; i < matchCollection.Count && i < replacementArray.Length; i++)
{
sourceString = sourceString.Replace(matchCollection[i].Value, replacementArray[i]);
}
[a-zA-Z_] describes a character class. For words, you'll have to add * at the end (any number of characters within a-zA-Z_.
Then, to have 'value1' captured, you'll need to add number support : [a-zA-Z0-9_]*, which can be summarized with: \w*
So try this one : {\w*}
But for replacing in C#, string.Split('/') might be easier as Fredrik proposed. Have a look at this too
You could use a delegate, something like this -
string[] strings = {"dog", "cat"};
int counter = -1;
string input = #"/home/{value1}/something/{anotherValue}";
Regex reg = new Regex(#"\{([a-zA-Z0-9]*)\}");
string result = reg.Replace(input, delegate(Match m) {
counter++;
return "{" + strings[counter] + "}";
});
My two cents:
// input string
string txt = "/home/{value1}/something/{anotherValue}";
// template replacements
string[] str_array = { "one", "two" };
// regex to match a template
Regex regex = new Regex("{[^}]*}");
// replace the first template occurrence for each element in array
foreach (string s in str_array)
{
txt = regex.Replace(txt, s, 1);
}
Console.Write(txt);

How to split string by string with multiple inverted commas in string in c#

How to split a string by "," where " is part of string to split by.
string[] stringSeparator = new string[] {","};
while (!sr.EndOfStream) {
string strline = sr.ReadLine();
string[] _values = strline.Split(stringSeparator, StringSplitOptions.None);
for (int entry = 0; entry < _values.Length; entry++) {
MessageBox.Show(_values[entry]);
}
}
Tried to use "","" but it seems to return whole line instead of just part of it.
Edit:
String to split (example):
First line:
"24446022020000000174234443,""PLN"",""NVESTMENT
SOMETHING
"",""2011-03-06"",""2011-03-07"",""-25,21"""
2nd line:
"1,""E"",""2011-03-04"",""2011-03-07"",""2011-03-07"",""1,00"",""0000000100000001"",""UZNANIE
sdsd
ELIXIR"",""45555550040000001244580001"",""Some
Client (E)KLIENT
NR:0000000100000001"",""example
something"",""73116022447246000100000001"""
If you want to represent literal quotation marks in a string, you need to escape it (or double it in a verbatim string literal).
i.e.,
new string[] { "\",\"" };
//or
new string[] { #""",""" };
As for why you're getting the values you were getting, consider the ways you were typing it:
string[] stringSeparator = new string[] { "," };
Is a string array containing a single string, just a comma ,. It will split but you probably didn't get the values you were expecting.
string[] stringSeparator = new string[] { "","" };
Is a string array containing a two strings, both empty (blank) strings. Perhaps it would be clearer if it was typed as: new string[] { "", "" };. The Split() function ignores empty string delimiters so it doesn't split anything.
string[] stringSeparator = new string[] { "\",\"" };
Is a string array containing a single string, double-quote comma double-quote ",". It should get you everything between the "," in your strings.
Try
char[] delimiters = new char[] { ',', '"' };
string[] parts = value.Split(delimiters,
StringSplitOptions.RemoveEmptyEntries);
Trim first and then split to get rid of all quotes.
string[] stringSeparator = new string[] {"\",\""};
while (!sr.EndOfStream)
{
//trim removes first and last quote since they are not removed by the split
string line = sr.ReadLine().Trim('"');
string[] values = line.Split(stringSeparator, StringSplitOptions.None);
for (int index = 0; index < values.Length; index++)
MessageBox.Show(values[index]);
}
string strline = sr.ReadLine();
string[] abc = strline.Split('"');
abc = Array.FindAll(abc, val => val != ",").ToArray();
string result[] = Array.FindAll(abc, val => val != "").ToArray();

Categories

Resources