I have a grid of two-digit numbers written as a string delimited with newlines and spaces, e.g.:
string grid = "58 96 69 22 \n" +
"87 54 21 36 \n" +
"02 26 08 15 \n" +
"88 09 12 45";
I would like to split it into a 4-by-4 array, so that I can access it via something like separatedGrid[i, j]. I know I can use grid.Split(' ') to separate the numbers in each row, but how do I get a 2-D array out of it?
So what you want is to convert a delimited multi-Line String into a 2D-Array:
string grid = "58 96 69 22 \n" +
"87 54 21 36 \n" +
"02 26 08 15 \n" +
"88 09 12 45";
var lines = grid.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim().Split(' ')).ToArray();
int numberOfRows = lines.Length;
int maxNumberOfColumns = lines.Max(x => x.Length);
string[,] separatedGrid = new string[numberOfRows, maxNumberOfColumns];
for (int i = 0; i < lines.Count(); i++)
{
string[] values = lines.ElementAt(i);
for (int j = 0; j < values.Length; j++)
{
separatedGrid.SetValue(values[j], i, j);
}
}
Yes use split like this:
string grid = "58 96 69 22 \n87 54 21 36 \n02 26 08 15 \n88 09 12 45";
var jagged = grid.Split('\n').Select(
x => new string[4] { x.Split(' ')[0], x.Split(' ')[1], x.Split(' ')[2], x.Split(' ')[3] }
).ToArray();
And if you want a 2-D Array:
var _2D = new String[jagged.Length, jagged[0].Length];
for (var i = 0; i != jagged.Length; i++)
for (var j = 0; j != jagged[0].Length; j++)
_2D[i, j] = jagged[i][j];
The result:
Related
I have a generic list of strings, but I know from 12 to 12 items I have a Record. I Also have a Model that want to populate.
My primary code
for (int r = 2; r <= rows; r++)
{
for (int c = 3; c <= cols; c++)
{
try
{
list.Add(usedRange.Cells[r, c].Value2.ToString());
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
foreach (string item in list)
{
}
So in foreach (string item in list) I know 12 the 24 then 36 my record is there
The problem is this peace of code
foreach (string item in list)
{
p.LastName = item
}
I need a for in order to populate my Model with all 12 items, I'm stuck
You can also get item each 12 elements with a for by index like this:
for (var i = 0; i < list.Count; i+=12)
var p.LastName = list[i];
If you want to have your list in chunks of 12 elements, you can use the Chunk Linq extension which is new in C# 10. An equivalent is available in the library MoreLinq if you don't use C# 10, it has a different name: Batch.
// Creating a sample list of dummy elements
// There will be 100 strings from "0" to "99".
var MyList = Enumerable.Range(0, 100)
.Select(i => $"{i}");
// Creating a list of chunks containing 12 elements
var ChunkedElements = MyList
.Chunk(12);
// Using the chunked list.
foreach (var chunk in ChunkedElements)
{
// Do what you want with the 12 elements
Console.WriteLine("New Chunk");
foreach(var e in chunk)
{
Console.WriteLine(e);
}
}
Output:
New Chunk
0
1
2
3
4
5
6
7
8
9
10
11
New Chunk
12
13
14
15
16
17
18
19
20
21
22
23
New Chunk
24
25
26
27
28
29
30
31
32
33
34
35
New Chunk
36
37
38
39
40
41
42
43
44
45
46
47
New Chunk
48
49
50
51
52
53
54
55
56
57
58
59
New Chunk
60
61
62
63
64
65
66
67
68
69
70
71
New Chunk
72
73
74
75
76
77
78
79
80
81
82
83
New Chunk
84
85
86
87
88
89
90
91
92
93
94
95
New Chunk
96
97
98
99
If you only want every 12th element, here is a Linq alternative to the classical for loops. It is not better or worst, but can be useful depending on the context.
// Creating a sample list of dummy elements
// There will be 100 strings from "0" to "99".
var MyList = Enumerable.Range(0, 100)
.Select(i => $"{i}");
// Filtering the list to get only the 12th elements
var FilteredElements = MyList
.Where((e, i) => i % 12 == 0);
// Using the filtered list
foreach (var e in FilteredElements)
{
// Here do what you want with each element.
Console.WriteLine(e);
}
Output:
0
12
24
36
48
60
72
84
96
Explanation:
.Where((e, i) => i % 12 == 0) is where the work is done. The linq extension method Where has an overload that takes as argument a Func<TSource, Int32, bool>. See the doc. The second parameter is the index of the element of the collection.
So .Where((e, i) => i % 12 == 0) keeps only the elements of the collection for which the index i is divisible by 12 (i % 12 == 0). Hence the result containing only multiples of 12.
For now is like this but I'll change it to a smother approach.
for (var i = 0; i < list.Count; i += 13)
{
p.Add(new Participants()
{
LastName = list[0+i],
FirstName = list[1 + i],
AddressType = list[2 + i],
Email = list[3 + i],
Company = list[4 + i],
Phone = list[5 + i],
Street = list[6 + i],
ZipCode = list[7 + i],
City = list[8 + i],
Country = list[9 + i],
Percent = list[10 + i],
Points = list[11 + i],
Passed = list[12 + i],
});
}
I have a text file that include of numbers and I save it in a string array.
one line of my text file is this:
2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114:275:5 8 1 14 10 6 10 18 12 25 7 40 1 30 18 8 2 1 5 21 10 2 21
every line save in one of indexes of string array.
now how can i access array elements as int type and search and calculate in all of array?
this is my array:
string [] lines = File.ReadAllLines(txtPath.Text);
for example I want to return indexes of array that include number'14' in all of array .
This is the easiest and clearest way to solve it. I commented so you can better understand what happens in the entire program.
class Program
{
static void Main(string[] args)
{
// this is your array of strings (lines)
string[] lines = new string[1] {
"2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114:275:5 8 1 14 10 6 10 18 12 25 7 40 1 30 18 8 2 1 5 21 10 2 21"
};
// this dictionary contains the line index and the list of indexes containing number 14
// in that line
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
// iterating over lines array
for (int i = 0; i < lines.Length; i++)
{
// creating the list of indexes and the dictionary key
List<int> indexes = new List<int>();
dict.Add(i, indexes);
// splitting the line by space to get numbers
string[] lineElements = lines[i].Split(' ');
// iterating over line elements
for (int j = 0; j < lineElements.Length; j++)
{
int integerNumber;
// checking if the string lineElements[j] is a number (because there also this case 114:275:5)
if (int.TryParse(lineElements[j], out integerNumber))
{
// if it is we check if the number is 14, in that case we add that index to the indexes list
if (integerNumber == 14)
{
indexes.Add(j);
}
}
}
}
// Printing out lines and indexes:
foreach (int key in dict.Keys)
{
Console.WriteLine(string.Format("LINE KEY: {0}", key));
foreach (int index in dict[key])
{
Console.WriteLine(string.Format("INDEX ELEMENT: {0}", index));
}
Console.WriteLine("------------------");
}
Console.ReadLine();
}
}
UPDATE 1:
As you requested:
special thanks for your clear answering.if i want to do search for all of my array elements what can i do? it means instead of only
number'14' i want to print indexes of all numbers that appear in
indexes
If you want to print all the indexes you should Console.WriteLine(j), that is the index of the inner for cycle, instead of checking the number value if (integerNumber == 14).
So, this is the program:
class Program
{
static void Main(string[] args)
{
// this is your array of strings (lines)
string[] lines = new string[1] {
"2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114:275:5 8 1 14 10 6 10 18 12 25 7 40 1 30 18 8 2 1 5 21 10 2 21"
};
// this dictionary contains the line index and the list of indexes containing number 14
// in that line
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
// iterating over lines array
for (int i = 0; i < lines.Length; i++)
{
// creating the list of indexes and the dictionary key
List<int> indexes = new List<int>();
dict.Add(i, indexes);
// splitting the line by space to get numbers
string[] lineElements = lines[i].Split(' ');
// iterating over line elements
for (int j = 0; j < lineElements.Length; j++)
{
// printing all indexes of the current line
Console.WriteLine(string.Format("Element index: {0}", j));
}
}
Console.ReadLine();
}
}
UPDATE 2:
As you requested:
if i want to search my line till first " : " apper and then search next line, what can i do?
You need to break the for cycle when you are on the element with :
class Program
{
static void Main(string[] args)
{
// this is your array of strings (lines)
string[] lines = new string[1] {
"2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114:275:5 8 1 14 10 6 10 18 12 25 7 40 1 30 18 8 2 1 5 21 10 2 21"
};
// this dictionary contains the line index and the list of indexes containing number 14
// in that line
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
// iterating over lines array
for (int i = 0; i < lines.Length; i++)
{
// creating the list of indexes and the dictionary key
List<int> indexes = new List<int>();
dict.Add(i, indexes);
// splitting the line by space to get numbers
string[] lineElements = lines[i].Split(' ');
// iterating over line elements
for (int j = 0; j < lineElements.Length; j++)
{
// I'm saving the content of lineElements[j] as a string
string element = lineElements[j];
// I'm checking if the element saved as string contains the string ":"
if (element.Contains(":"))
{
// If it does, I'm breaking the cycle, and I'll continue with the next line
break;
}
int integerNumber;
// checking if the string lineElements[j] is a number (because there also this case 114:275:5)
if (int.TryParse(lineElements[j], out integerNumber))
{
// if it is we check if the number is 14, in that case we add that index to the indexes list
if (integerNumber == 14)
{
indexes.Add(j);
}
}
}
}
// Printing out lines and indexes:
foreach (int key in dict.Keys)
{
Console.WriteLine(string.Format("LINE KEY: {0}", key));
foreach (int index in dict[key])
{
Console.WriteLine(string.Format("INDEX ELEMENT: {0}", index));
}
Console.WriteLine("------------------");
}
Console.ReadLine();
}
}
As you can see, if you run this piece of code and compare it with the first version, in output you'll get only the index of the first 14 occurrence, because the second one is after the string with :.
First you must get all conttent of file in the string array format:
public string[] readAllInFile(string filepath){
var lines = File.ReadAllLines(path);
var fileContent = string.Join(' ',lines);//join all lines of file content in one variable
return fileContent.Split(' ');//each word(in your case each number) in one index of array
}
and in usage time you can do like this:
var MyFileContent = readAllInFile(txtPath.Text);
int x= Convert.ToInt32(MyFileContent[2]);
IEnumerable<int> numbers = MyFileContent.Select(m=> int.Parse(m);)
var sumeOf = numbers.sum();
you can use linq to have more tools on collections.
var linesAsInts = lines.Select(x => x.Split(' ').Select(int.Parse));
var filteredLines = linesAsInts.Where(x => x.Contains(14));
// define value delimiters.
var splitChars = new char[] { ' ', ':' };
// read lines and parse into enumerable of enumerable of ints.
var lines = File.ReadAllLines(txtPath.Text)
.Select(x => x.Split(splitChars)
.Select(int.Parse));
// search in array.
var occurences = lines
.Select((line,lineIndex) => line
.Select((integer, integerIndex) => new { integer, integerIndex })
.Where(x => x.integer == 10)
.Select(x => x.integerIndex));
// calculate all of array.
var total = lines.Sum(line => line.Sum());
I didn't know exactly how to ask this question better so I will try to explain it as best as I can.
Let's say I have one list of 20 strings myList1<string> and I have another string string ToCompare. Now each of the strings in the list as well as the string ToCompare have 8 words divided by empty spaces. I want to know how many times combination of any three words from string ToCompare in any possible order is to be found in the strings of myList1<string>. For an example:
This is the list (short version - example):
string1 = "AA BB CC DD EE FF GG HH";
string2 = "BB DD EE AA HH II JJ MM";
.......
string20 = "NN OO AA RR EE BB FF KK";
string ToCompare = "BB GG AA FF CC MM RR II";
Now I want to know how many times any combination of 3 words from ToCompare string is to be found in myList1<string>. To clarify futher three words from ToCompare "BB AA CC" are found in string1 of the list thus the counter for these 3 words would be 1. Another 3 words from ToCompare "BB AA II" are found in the string2 of myList1<string> but the counter here would be also 1 because it's not the same combination of words (I have "AA" and "BB" but also "II". They are not equal). Order of these 3 words doesn't matter, that means "AA BB CC" = "BB AA CC" = "CC BB AA". I want to know how many combinations of all (any) 3 words from ToCompare are found in myList1<string>. I hope it's clear what I mean.
Any help would be appreciated, I don't have a clue how to solve this. Thanks.
Example from Vanest:
List<string> source = new List<string>();
source.Add("2 4 6 8 10 12 14 99");
source.Add("16 18 20 22 24 26 28 102");
source.Add("33 6 97 38 50 34 87 88");
string ToCompare = "2 4 6 15 20 22 28 44";
The rest of the code is exacty the same, and the result:
Key = 2 4 6, Value = 2
Key = 2 4 20, Value = 1
Key = 2 4 22, Value = 1
Key = 2 4 28, Value = 1
Key = 2 6 20, Value = 1
Key = 2 6 22, Value = 1
Key = 2 6 28, Value = 1
Key = 2 20 22, Value = 1
Key = 2 20 28, Value = 1
Key = 2 22 28, Value = 1
Key = 4 6 20, Value = 1
Key = 4 6 22, Value = 1
Key = 4 6 28, Value = 1
Key = 4 20 22, Value = 1
Key = 4 20 28, Value = 1
Key = 4 22 28, Value = 1
Key = 6 20 22, Value = 1
Key = 6 20 28, Value = 1
Key = 6 22 28, Value = 1
Key = 20 22 28, Value = 1
As you can see there are combinations which not exist in the strings, and the value of the first combination is 2 but it comes only one time in the first string
I think this should suffice your ask,
List<string> source = new List<string>();
source.Add("AA BB CC DD EE FF GG HH");
source.Add("BB DD EE AA HH II JJ MM");
source.Add("NN OO AA RR EE BB FF KK");
string ToCompare = "BB GG AA FF CC MM RR II";
string word1, word2, word3, existingKey;
string[] compareList = ToCompare.Split(new string[] { " " }, StringSplitOptions.None);
Dictionary<string, int> ResultDictionary = new Dictionary<string, int>();
for (int i = 0; i < compareList.Length - 2; i++)
{
word1 = compareList[i];
for (int j = i + 1; j < compareList.Length - 1; j++)
{
word2 = compareList[j];
for (int z = j + 1; z < compareList.Length; z++)
{
word3 = compareList[z];
source.ForEach(x =>
{
if (x.Contains(word1) && x.Contains(word2) && x.Contains(word3))
{
existingKey = ResultDictionary.Keys.FirstOrDefault(y => y.Contains(word1) && y.Contains(word2) && y.Contains(word3));
if (string.IsNullOrEmpty(existingKey))
{
ResultDictionary.Add(word1 + " " + word2 + " " + word3, 1);
}
else
{
ResultDictionary[existingKey]++;
}
}
});
}
}
}
ResultDictionary will have the 3 word combinations that occur in myList1<string> with their count of occurrences. To get the total count, retrieve and add all the value fields from ResultDictionary.
EDIT:
Below snippet produces correct result with the given input,
List<string> source = new List<string>();
source.Add("2 4 6 8 10 12 14 99");
source.Add("16 18 20 22 24 26 28 102");
source.Add("33 6 97 38 50 34 87 88");
string ToCompare = "2 4 6 15 20 22 28 44";
string word1, word2, word3, existingKey;
string[] compareList = ToCompare.Split(new string[] { " " }, StringSplitOptions.None);
string[] sourceList, keywordList;
Dictionary<string, int> ResultDictionary = new Dictionary<string, int>();
source.ForEach(x =>
{
sourceList = x.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < compareList.Length - 2; i++)
{
word1 = compareList[i];
for (int j = i + 1; j < compareList.Length - 1; j++)
{
word2 = compareList[j];
for (int z = j + 1; z < compareList.Length; z++)
{
word3 = compareList[z];
if (sourceList.Contains(word1) && sourceList.Contains(word2) && sourceList.Contains(word3))
{
existingKey = ResultDictionary.Keys.FirstOrDefault(y =>
{
keywordList = y.Split(new string[] { " " }, StringSplitOptions.None);
return keywordList.Contains(word1) && keywordList.Contains(word2) && keywordList.Contains(word3);
});
if (string.IsNullOrEmpty(existingKey))
{
ResultDictionary.Add(word1 + " " + word2 + " " + word3, 1);
}
else
{
ResultDictionary[existingKey]++;
}
}
}
}
}
});
Hope this helps...
I think this will do what you're asking for:
void Main()
{
var list =
new List<String>
{
"AA BB CC DD EE FF GG HH",
"BB DD EE AA HH II JJ MM",
"NN OO AA RR EE BB FF KK"
};
var toCompare = "BB GG AA FF CC MM RR II";
var permutations = CountPermutations(list, toCompare);
}
public Int32 CountPermutations(List<String> list, String compare)
{
var words = compare.Split(' ');
return list
.Select(l => l.Split(' '))
.Select(l => new { String = String.Join(" ", l), Count = l.Join(words, li => li, wi => wi, (li, wi) => li).Count()})
.Sum(x => x.Count - 3);
}
[edit: 2/20/2019]
You can use the following to get all the matches to each list item with the total number of unique combinations
void Main()
{
var list =
new List<String>
{
"AA BB CC DD EE FF GG HH",
"BB DD EE AA HH II JJ MM",
"NN OO AA RR EE BB FF KK",
"AA AA CC DD EE FF GG HH"
};
list.Select((l, i) => new { Index = i, Item = l }).ToList().ForEach(x => Console.WriteLine($"List Item{x.Index + 1}: {x.Item}"));
var toCompare = "BB GG AA FF CC MM RR II";
Console.WriteLine($"To Compare: {toCompare}");
Func<Int32, Int32> Factorial = x => x < 0 ? -1 : x == 0 || x == 1 ? 1 : Enumerable.Range(1, x).Aggregate((c, v) => c * v);
var words = toCompare.Split(' ');
var matches = list
// Get a list of the list items with all their parts
.Select(l => new { Parts = l.Split(' '), Original = l })
// Join each part from the to-compare item to each part of the list item
.Select(l => new { String = String.Join(" ", l), Matches = l.Parts.Join(words, li => li, wi => wi, (li, wi) => li), l.Original })
// Only consider items with at least 3 matches
.Where(l => l.Matches.Count() >= 3)
// Get the each item including how many parts matched and how many unique parts there are of each part
.Select(l => new { l.Original, Matches = String.Join(" ", l.Matches), Count = l.Matches.Count(), Groups = l.Matches.GroupBy(m => m).Select(m => m.Count()) })
// To calculate the unique combinations for each match use the following mathematical equation: match_count! / (frequency_part_1! * frequency_part_2! * ... * frequency_part_n!)
.Select(l => new { l.Original, l.Matches, Combinations = Factorial(l.Count) / l.Groups.Aggregate((c, v) => c * Factorial(v)) })
.ToList();
matches.ForEach(m => Console.WriteLine($"Original: {m.Original}, Matches: {m.Matches}, Combinations: {m.Combinations}"));
var totalUniqueCombinations = matches.Sum(x => x.Combinations);
Console.WriteLine($"Total Unique Combinations: {totalUniqueCombinations}");
}
The problem I'm trying to solve is like this.
I'm given N, telling me the range of numbers is 0, 1, ..., N-2, N-1.
I'm also given pairings, telling me that those number pairs are in the same "group".
Ex:
N=6, 0 and 1 are paired, 1 and 4 are paired, and 2 and 3 are paired, and I know that the remaining numbers are in their own groups.
Then I know the groupings are {0, 1, 4}, {2, 3}, {5}.
The number of ways to choose two numbers from different groups among these groups is 11 and that's the number I'm trying to solve for. These choices are:
{0,2},
{0,3},
{0,5},
{1,2},
{1,3},
{1,5},
{4,2},
{4,3},
{4,5},
{2,5},
{3,5}
Can someone help figure out where my logic is wrong? Because I'm failing larger test cases and passing smaller ones.
My code:
static int Combinations(int N, int K)
{
decimal result = 1;
for (int i = 1; i <= K; i++)
{
result *= N - (K - i);
result /= i;
}
return (int)result;
}
/// <summary>
/// Given a set of n numbers 0, 1, ..., n-1 and a list of pairs
/// of the numbers from the set where each pair (i,j) means that
/// number i and j are in the same group, find the number of ways
/// to choose 2 numbers that are not in the same group.
/// </summary>
static int PoliticallyCorrectPairs(int n, Tuple<int, int>[] pairs)
{
// Create a map that from each number to a number representing
// the group that it is in. For example, if n = 5 and
// pairs = { (0, 1), (2, 3), (0, 4) }, then the map will look
// like
// 0 -> 1
// 1 -> 1
// 2 -> 2
// 3 -> 2
// 4 -> 1
// indicating that 0,1,4 belong to one group and 2,3 to the other.
int[] gmap = new int[n];
int k = 1;
foreach(Tuple<int, int> pair in pairs)
{
int i = pair.Item1,
j = pair.Item2;
// If both i and j are already in groups, combine those into a
// single group if it isn't already.
if (gmap[i] != 0 && gmap[j] != 0)
{
if(gmap[i] != gmap[j])
{
for(int m = 0; m < n; ++m)
if(gmap[m] == gmap[j])
gmap[m] = gmap[i];
}
}
else if(gmap[j] != 0) // j is in a group and i isn't
gmap[i] = gmap[j]; // add i to j's group
else if(gmap[i] != 0) // i is in a group and j isn't
gmap[j] = gmap[i]; // add j to i's group
else
gmap[i] = gmap[j] = k++; // Put both in same new group.
}
// Those not assigned to a group each end up in a group alone.
for(int i = 0; i < gmap.Length; ++i)
if(gmap[i] == 0)
gmap[i] = k++;
// Get the group sizes as an array.
int[] gcnts = gmap.GroupBy(x => x).Select(g => g.Count()).ToArray();
// Total number of ways to choose pairs of numbers.
int totalCombinations = Combinations(n, 2);
// Number of pairs from previous count that are in the same group.
int impossibleCombinations = gmap.GroupBy(x => x)
.Select(g => g.Count())
.Where(count => count > 1)
.Sum(count => Combinations(count, 2));
return totalCombinations - impossibleCombinations;
}
For example, I am passing
[TestMethod]
public void Sample1()
{
int N = 5;
Tuple<int, int>[] pairs = new Tuple<int, int>[]
{
Tuple.Create(0, 1),
Tuple.Create(2, 3),
Tuple.Create(0, 4)
};
Assert.AreEqual(6, PoliticallyCorrectPairs(N, pairs));
}
but failing
[TestMethod]
public void TestCase2()
{
int N = 100;
Tuple<int, int>[] pairs =
#"0 11
2 4
2 95
3 48
4 85
4 95
5 67
5 83
5 42
6 76
9 31
9 22
9 55
10 61
10 38
11 96
11 41
12 60
12 69
14 80
14 99
14 46
15 42
15 75
16 87
16 71
18 99
18 44
19 26
19 59
19 60
20 89
21 69
22 96
22 60
23 88
24 73
27 29
30 32
31 62
32 71
33 43
33 47
35 51
35 75
37 89
37 95
38 83
39 53
41 84
42 76
44 85
45 47
46 65
47 49
47 94
50 55
51 99
53 99
56 78
66 99
71 78
73 98
76 88
78 97
80 90
83 95
85 92
88 99
88 94"
.Split('\n')
.Select(line =>
{
int[] twofer = line.Split(' ').Select(s => int.Parse(s)).ToArray();
return Tuple.Create(twofer[0], twofer[1]);
})
.ToArray();
Assert.AreEqual(3984, PoliticallyCorrectPairs(N, pairs));
}
Any idea where I'm going wrong?
The problem is in the combining part:
if(gmap[i] != gmap[j])
{
for(int m = 0; m < n; ++m)
if(gmap[m] == gmap[j]) // here
gmap[m] = gmap[i];
}
When m hits j, the gmap[j] is replaced with gmap[i], hence the rest of the elements are checked against gmap[i].
Simply put the replaced value into local variable:
if(gmap[i] != gmap[j])
{
int g = gmap[j];
for(int m = 0; m < n; ++m)
if(gmap[m] == g)
gmap[m] = gmap[i];
}
Assumed that I have below string
[["Fri, 28 Mar 2014 01:00:00 +0000",0.402053266764,"1 sold"],["Thu, 03 Apr 2014 01:00:00 +0000",6.5,"1 sold"]];
How can i assign this set of string into an array?
Expected result:
string[,] items = {
{ "Fri, 28 Mar 2014 01:00:00 +0000", "0.402053266764", "1 sold"},
{ "Thu, 03 Apr 2014 01:00:00 +0000", "6.5", "1 sold"}
}
A brute force attack, probably better solutions are available
string input ="[[\"Fri, 28 Mar 2014 01:00:00 +0000\",0.402053266764,\"1 sold\"],[\"Thu, 03 Apr 2014 01:00:00 +0000\",6.5,\"1 sold\"]]";
string temp = input.Replace("[", "");
string[] records = temp.Split(new char[] {']'}, StringSplitOptions.RemoveEmptyEntries);
string[,] output = new string[records.Length, 3];
int recno = 0;
foreach(string record in records)
{
Console.WriteLine(record);
string[] fields = record.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
output[recno,0] = string.Join(",", fields[0], fields[1]);
output[recno,1] = fields[2];
output[recno,2] = fields[3];
recno++;
}
for(int x = 0; x <= output.GetUpperBound(0); x++)
{
for(int y = 0; y <= output.GetUpperBound(1); y++)
Console.Write("INDEX[" +x + "," + y +"]=" + output[x, y] + ";");
Console.WriteLine();
}
string inputString; //Your original string
inputString=inputString.Replace('[',' '); //Removes left bracket
inputString=inputString.Substring(0,inputString.Count()-2); //Removes last two right brakets
var arrayOfStrings=inputString.Split(']'); //Split on right bracket
for(int i=1; i < arrayOfStrings.Count() -1; i++){
arrayOfStrings[i]=arrayOfStrings[i].Substring(1); //Removes the "," at the start of the 2nd to the n-1th elements
}