C# easy way to convert a split string into columns - c#

This is a rough one to explain. What I have is a string,
string startString = "Operations\t325\t65\t0\t10\t400"
string[] splitStart = startString.Split('\t');
I need to turn this into
Operations|325
Operations|65
Operations|0
Operations|10
Operations|400
The problem is i need this so be dynamic to if it has 10 splits I need it to do the same process 10 times, if it has 4, then it needs to do 4.
Any help would be awesome.
Sorry for any confusion, Operations is just this string, so it's not static. It really need to be [0] of the string split.

Something like:
string startString = "Operations\t325\t65\t0\t10\t400"
string[] splitStart = startString.Split('\t');
List<string> result = new List<string>();
if(splitStart.Length > 1)
for(int i = 1; i < splitStart.Length; i++)
{
result.Add(splitStart[0] + "|" + splitStart[i]);
}

If it is the strings you want, a little Linq should be fine:
string startString = "Operations\t325\t65\t0\t10\t400";
var operations = startString.Split('\t').Select(str => "Operations|" + str);

How about this?
var reFormatted = new List<string>();
foreach (var roughOne in toExplain)
{
// example of roughOne "Operations\t325\t65\t0\t10\t400"
var segments = roughOne.Split("\t");
var firstSegment = segments.First();
var sb = new StringBuilder();
foreach (var otherSegment in segments.Skip(1))
{
sb.Append(firstSegment);
sb.Append("|")
sb.Append(otherSegment);
sb.Append("\r\n");
}
reFormatted.Add(sb.ToString());
}

Related

How can I split a string to store contents in two different arrays in c#?

The string I want to split is an array of strings.
the array contains strings like:
G1,Active
G2,Inactive
G3,Inactive
.
.
G24,Active
Now I want to store the G's in an array, and Active or Inactive in a different array. So far I have tried this which has successfully store all the G's part but I have lost the other part. I used Split fucntion but did not work so I have tried this.
int i = 0;
for(i = 0; i <= grids.Length; i++)
{
string temp = grids[i];
temp = temp.Replace(",", " ");
if (temp.Contains(' '))
{
int index = temp.IndexOf(' ');
grids[i] = temp.Substring(0, index);
}
//System.Console.WriteLine(temp);
}
Please help me how to achieve this goal. I am new to C#.
If I understand the problem correctly - we have an array of strings Eg:
arrayOfStrings[24] =
{
"G1,Active",
"G2,Inactive",
"G3,Active",
...
"G24,Active"
}
Now we want to split each item and store the g part in one array and the status into another.
Working with arrays the solution is to - traverse the arrayOfStrings.
Per each item in the arrayOfStrings we split it by ',' separator.
The Split operation will return another array of two elements the g part and the status - which will be stored respectively into distinct arrays (gArray and statusArray) for later retrieval. Those arrays will have a 1-to-1 relation.
Here is my implementation:
static string[] LoadArray()
{
return new string[]
{
"G1,Active",
"G2,Inactive",
"G3,Active",
"G4,Active",
"G5,Active",
"G6,Inactive",
"G7,Active",
"G8,Active",
"G9,Active",
"G10,Active",
"G11,Inactive",
"G12,Active",
"G13,Active",
"G14,Inactive",
"G15,Active",
"G16,Inactive",
"G17,Active",
"G18,Active",
"G19,Inactive",
"G20,Active",
"G21,Inactive",
"G22,Active",
"G23,Inactive",
"G24,Active"
};
}
static void Main(string[] args)
{
string[] myarrayOfStrings = LoadArray();
string[] gArray = new string[24];
string[] statusArray = new string[24];
int index = 0;
foreach (var item in myarrayOfStrings)
{
var arraySplit = item.Split(',');
gArray[index] = arraySplit[0];
statusArray[index] = arraySplit[1];
index++;
}
for (int i = 0; i < gArray.Length; i++)
{
Console.WriteLine("{0} has status : {1}", gArray[i] , statusArray[i]);
}
Console.ReadLine();
}
seems like you have a list of Gxx,Active my recomendation is first of all you split the string based on the space, which will give you the array previoulsy mentioned doing the next:
string text = "G1,Active G2,Inactive G3,Inactive G24,Active";
string[] splitedGItems = text.Split(" ");
So, now you have an array, and I strongly recommend you to use an object/Tuple/Dictionary depends of what suits you more in the entire scenario. for now i will use Dictionary as it seems to be key-value
Dictionary<string, string> GxListActiveInactive = new Dictionary<string, string>();
foreach(var singleGItems in splitedGItems)
{
string[] definition = singleGItems.Split(",");
GxListActiveInactive.Add(definition[0], definition[1]);
}
What im achiving in this code is create a collection which is key-value, now you have to search the G24 manually doing the next
string G24Value = GxListActiveInactive.FirstOrDefault(a => a.Key == "G24").Value;
just do it :
var splitedArray = YourStringArray.ToDictionary(x=>x.Split(',')[0],x=>x.Split(',')[1]);
var gArray = splitedArray.Keys;
var activeInactiveArray = splitedArray.Values;
I hope it will be useful
You can divide the string using Split; the first part should be the G's, while the second part will be "Active" or "Inactive".
int i;
string[] temp, activity = new string[grids.Length];
for(i = 0; i <= grids.Length; i++)
{
temp = grids[i].Split(',');
grids[i] = temp[0];
activity[i] = temp[1];
}

How to make string list to "string array"

This is what I want to convernt: {"apple", "banana"} to "["apple", "banana"]"
I have tried convert string list to string array first, then convert string array to string, but did not work.
var testing = new List<string> {"apple", "banana"};
var arrayTesting = testing.ToArray();
var result = arrayTesting.ToString();
You can use string.Join(String, String[]) method like below to get a , separated string values (like csv format)
var stringifiedResult = string.Join(",", result);
You can try this, should work;
var testing = new List<string> { "apple", "banana" };
var arrayTesting = testing.ToArray<string>();
var result = string.Join(",", arrayTesting);
You can also use StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("\"[");
for (int i = 0; i < arrayTesting.Length; i++)
{
string item = arrayTesting[i];
sb.Append("\"");
sb.Append(item);
if (i == arrayTesting.Length - 1)
{
sb.Append("\"]");
}
else
sb.Append("\",");
}
Console.WriteLine(sb);
Instead of converting it to an array, you could use a linq operator on the list to write all the values into a string.
string temp = "";
testing.ForEach(x => temp += x + ", ");
This will leave you with a single string with each value in the list separated by a comma.

Remove trailing pipes - '|' in c#

I have a string that looks something like this:
"PID||000000|Z123345|23345|SOMEONE^FIRSTNAME^^^MISS^||150|F|1111||1 DREYFUS CLOSE^SOUTH CITY^COUNTY^^POST CODE^^^||0123 45678910^PRN^PH^^^^0123 45678910^^~^^CP^^^^^^~^NET^^^^^^^||||1A|||||A||||||||N||||||||||";
I am trying to remove any separating '|' characters after the 30th '|' in the string so that the output string looks like this:
"PID||000000|Z123345|23345|SOMEONE^FIRSTNAME^^^MISS^||150|F|1111||1 DREYFUS CLOSE^SOUTH CITY^COUNTY^^POST CODE^^^||0123 45678910^PRN^PH^^^^0123 45678910^^~^^CP^^^^^^~^NET^^^^^^^||||1A|||||A||||||||N";
I am trying to do it using as little code as possible, but not having much luck. Any help or ideas would be great.
You can use the TrimEnd method
string text = "stuff||||N||||||||||";
string result = text.TrimEnd('|'); //Result is stuff||||N
Brute force but only a little bit of code:
string s2 = string.Join("|", s1.Split('|').Take(31));
If you need any other processing of this kind of data (it looks like a kind of nested CSV) then string.Split() is useful to know.
string str = "PID||000000|Z123345|23345|SOMEONE^FIRSTNAME^^^MISS^||150|F|1111||1 DREYFUS CLOSE^SOUTH CITY^COUNTY^^POST CODE^^^||0123 45678910^PRN^PH^^^^0123 45678910^^~^^CP^^^^^^~^NET^^^^^^^||||1A|||||A||||||||N||||||||||";
int c = 0;
int after = 30;
StringBuilder newStr = new StringBuilder();
for(int i = 0;i < str.length; i++){
if(str[i] == '|'){
if(after != c){
newStr.append(str[i]);
c++;
}
}else{
newStr.append(str[i]);
}
}
results in
newStr == "PID||000000|Z123345|23345|SOMEONE^FIRSTNAME^^^MISS^||150|F|1111||1 DREYFUS CLOSE^SOUTH CITY^COUNTY^^POST CODE^^^||0123 45678910^PRN^PH^^^^0123 45678910^^~^^CP^^^^^^~^NET^^^^^^^||||1A|||||A||||||||N";
A regex should do the trick:
var regex = new Regex(#"^([^\|]*\|){0,30}[^\|]*");
var match = regex.Match(input);
if(match.Success)
{
var val = match.Value;
}
If what you really want is that everything after the 30th chunk loses its '|', then try:
var chunks = input.Split('|');
var output = String.Join('|',chunks.Take(30)) + String.Concat(chunks.Skip(30));
That said, I think it sounds like what you're really looking for is probably something like:
var output = input.TrimEnd('|');
// Get the indexes of all the | characters.
int[] pipeIndexes = Enumerable.Range(0, s.Length).Where(i => s[i] == '|').ToArray();
// If there are more than thirty pipes:
if (pipeIndexes.Length > 30)
{
// The former part of the string remains intact.
string formerPart = s.Substring(0, pipeIndexes[30]);
// The latter part needs to have all | characters removed.
string latterPart = s.Substring(pipeIndexes[30]).Replace("|", "");
s = formerPart + latterPart;
}

Split string with ' in C#

How to split this string
1014,'0,1031,1032,1034,1035,1036',0,0,1,1,0,1,0,-1,1
and get this string array as result
1014
'0,1031,1032,1034,1035,1036'
0
0
1
1
0
1
0
-1
1
in C#
I believe that this regex should give you what you are looking for:
('(?:[^']|'')*'|[^',\r\n]*)(,|\r\n?|\n)?
http://regexr.com?2vib4
EDIT:
Quick code snippet on how it might work:
var rx = new Regex("('(?:[^']|'')*'|[^',\r\n]*)(,|\r\n?|\n)?");
var text= "1014,'0,1031,1032,1034,1035,1036',0,0,1,1,0,1,0,-1,1";
var matches = rx.Matches(text);
foreach (Match match in matches)
{
System.Console.WriteLine(match.Groups[1].ToString());
}
try this,
string line ="1014,'0,1031,1032,1034,1035,1036',0,0,1,1,0,1,0,-1,1" ;
var values = Regex.Matches(line, "(?:'(?<m>[^']*)')|(?<m>[^,]+)");
foreach (Match value in values) {
Console.WriteLine(value.Groups["m"].Value);
}
This code is not pretty at all, but it works. :) (Does not work with multiple "strings" within the string.)
void Main()
{
string stuff = "1014,'0,1031,1032,1034,1035,1036',0,0,1,1,0,1,0,-1,1";
List<string> newStuff = new List<string>();
var extract = stuff.Substring(stuff.IndexOf('\''), stuff.IndexOf('\'', stuff.IndexOf('\'') + 1) - stuff.IndexOf('\'') + 1);
var oldExtract = extract;
extract = extract.Replace(',',';');
stuff = stuff.Replace(oldExtract, extract);
newStuff.AddRange(stuff.Split(new[] {','}));
var newList = newStuff;
for(var i = 0; i < newList.Count; i++)
newList[i] = newList[i].Replace(';',',');
// And newList will be in the format you specified, but in a list..
}
Firstly split a string on ' (single) quote and then after go for comma (,).
You don't need a parser, you don't need Regex. Here's a pretty simple version that works perfectly:
var splits = input
.Split('\'')
.SelectMany(
(s,i) => (i%2==0)
? s.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries)
: new[]{ "'" + s + "'"}
);
This is exactly what #AVD + #Rawling described ... Split on ', and split only "even" results, then combine.
using System;
using System.IO;
using Microsoft.VisualBasic.FileIO; //Microsoft.VisualBasic.dll
public class Sample {
static void Main(){
string data = "1014,'0,1031,1032,1034,1035,1036',0,0,1,1,0,1,0,-1,1";
string[] fields = null;
data = data.Replace('\'', '"');
using(var csvReader = new TextFieldParser(new StringReader(data))){
csvReader.SetDelimiters(new string[] {","});
csvReader.HasFieldsEnclosedInQuotes = true;
fields = csvReader.ReadFields();
}
foreach(var item in fields){
Console.WriteLine("{0}",item);
}
}
}

Extracting variable number of token pairs from a string to a pair of arrays

Here is the requirement.
I have a string with multiple entries of a particular format. Example below
string SourceString = "<parameter1(value1)><parameter2(value2)><parameter3(value3)>";
I want to get the ouput as below
string[] parameters = {"parameter1","parameter2","parameter3"};
string[] values = {"value1","value2","value3"};
The above string is just an example with 3 pairs of parameter values. The string may have 40, 52, 75 - any number of entries (less than 100 in one string).
Like this I have multiple strings in an array. I want to do this operation for all the strings in the array.
Could any one please advice how to achieve this? I'm a novice in c#.
Is using regex a better solution or is there any other method?
Any help is much appreciated.
If you didn't like RegEx's you could do something like this:
class Program
{
static void Main()
{
string input = "<parameter1(value1)>< parameter2(value2)>";
string[] Items = input.Replace("<", "").Split('>');
List<string> parameters = new List<string>();
List<string> values = new List<string>();
foreach (var item in Items)
{
if (item != "")
{
KeyValuePair<string, string> kvp = GetInnerItem(item);
parameters.Add(kvp.Key);
values.Add(kvp.Value);
}
}
// if you really wanted your results in arrays
//
string[] parametersArray = parameters.ToArray();
string[] valuesArray = values.ToArray();
}
public static KeyValuePair<string, string> GetInnerItem(string item)
{
//expects parameter1(value1)
string[] s = item.Replace(")", "").Split('(');
return new KeyValuePair<string, string>(s[0].Trim(), s[1].Trim());
}
}
It might be a wee bit quicker than the RegEx method but certainly not as flexible.
You could use RegEx class in combination with an expression to parse the string and generate these arrays by looping through MatchCollections.
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx
This does it:
string[] parameters = null;
string[] values = null;
// string SourceString = "<parameter1(value1)><parameter2(value2)><parameter3(value3)>";
string SourceString = #"<QUEUE(C2.BRH.ARB_INVPUSH01)><CHANNEL(C2.MONITORING_CHANNEL)><QMGR(C2.MASTER_NA‌​ME.TRACKER)>";
// string regExpression = #"<([^\(]+)[\(]([\w]+)";
string regExpression = #"<([^\(]+)[\(]([^\)]+)";
Regex r = new Regex(regExpression);
MatchCollection collection = r.Matches(SourceString);
parameters = new string[collection.Count];
values = new string[collection.Count];
for (int i = 0; i < collection.Count; i++)
{
Match m = collection[i];
parameters[i] = m.Groups[1].Value;
values[i] = m.Groups[2].Value;
}

Categories