Error in string.join while creating a multi dimensional array - c#

I have created a multi-dimensional array:
string[,] array_questions = new string[dt.Rows.Count, dt.Columns.Count];
for (i = 0; i < dt.Rows.Count; i++)
{
for (j = 0; j < dt.Columns.Count; j++)
{
array_questions[i, j] = dt.Rows[i][j].ToString();
//Response.Write(array_questions[i, j]);
}
// Response.Write(Environment.NewLine);
//Response.Write("\n");
}
foreach (string number in array_questions)
{
//Response.Write(number + " ");
//Response.Write(Environment.NewLine);
Response.Write(string.Join(", ", number) + Environment.NewLine);
}
but it shows an error like : Error 1 The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments.. Please help

You do not need a for loop to join the string.
string.Join(", ", array_questions)
Replace the code
foreach (string number in array_questions)
{
//Response.Write(number + " ");
//Response.Write(Environment.NewLine);
Response.Write(string.Join(", ", number) + Environment.NewLine);
}
with
Response.Write(string.Join(", ", array_questions) + Environment.NewLine);

You need to flatten your array to use string.Join. It takes the separator and a single dimensional array, so you may proabably need to do something like this. But not sure what you are trying to achieve here. You are trying to call string.Join(string, string[]) as string.Join(string, string)
Try something like this:
var sdArray= new List<string>();
for (var i = 0; i < dt.Rows.Count; i++) //Get the length of first Dimension
{
for (var j = 0; j < dt.Columns.Count; j++) //Get the length of second Dimension
{
sdArray.Add(array_questions[i, j]);
}
}
///
Response.Write(string.Join(", ", sdArray) + Environment.NewLine);
Using Linq you can flatten this in a better way.
Something like this
string joinedSetOfQns= string.Join(",",
Enumerable.Range(0, dt.Rows.Count)
.SelectMany(i => Enumerable.Range(0, dt.Columns.Count)
.Select(j => array_questions[i, j])));
Response.Write(joinedSetOfQns + Environment.NewLine);
This is the defenision for string.Join
public static string Join(
string separator,
params string[] value /// <-- Takes single Dimensional Array not a string.
)
Update: Since you need to join Rowwise
for (var i = 0; i < dt.Rows.Count; i++)
{
var result = new List<string>();
for (var j = 0; j < dt.Columns.Count; j++)
{
result.Add(array_questions[i, j]);
}
Response.Write(string.Join(", ", result) + Environment.NewLine);
}

Related

C# find the count of duplicate characters in an array and list them

I am trying to find the number of duplicate characters in an array and list them. For example, the user enters "this is my house", the output should look like this:
Number of duplicate characters is: 3 and the duplicates are: h i s
I have to use ToCharArray()
I've been trying but I can't get it to work properly, can you please help?
Thanks
Here is my code:
using System;
class Program
{
static void Main()
{
Console.Write("type a sentence: ");
String str = Console.ReadLine();
char[] arr = str.ToCharArray();
for (int j = 0; j < arr.Length; j++)
{
for (int k = j + 1; k < arr.Length; k++)
{
if (arr[j] == arr[k] && j != k)
{
Console.WriteLine("number of duplicates: " + k + "\n" + "duplicates are: " + arr[j]);
Console.ReadLine();
}
}
}
}
}
You can try to use linq instead of for loop.
GroupBy make a group and use where get count greater than 1.
var r= str.Replace(" ", "").GroupBy(_ => _).Where(x => x.Count() > 1).Select(x => x.Key);
then use string.Join method and linq count instead of a loop to get your expect result.
Console.Write("type a sentence: ");
String str = Console.ReadLine();
var result = str.Replace(" ", "")
.GroupBy(_ => _)
.Where(x => x.Count() > 1)
.Select(x => x.Key);
Console.WriteLine("number of duplicates: " + result.Count() + "\r" + "duplicates are: " + string.Join(" ",result));
c# online
Result
type a sentence: number of duplicates: 3 duplicates are: h i s
Here is another solution without linq:
static void Main(string[] args)
{
string longText = #"your sentence comes here";
foreach (var character in CharacterCount.Count(longText))
{
if(character.Value>1)
Console.WriteLine("{0} - {1}", character.Key, character.Value);
}
}
class CharacterCount
{
public static SortedDictionary<char, ulong> Count(string stringToCount)
{
SortedDictionary<char, ulong> characterCount = new SortedDictionary<char, ulong>();
foreach (var character in stringToCount)
{
if (!characterCount.ContainsKey(character))
characterCount.Add(character, 1);
else
characterCount[character]++;
}
return characterCount;
}
}
This may help.
Console.Write("type a sentence: ");
String str = Console.ReadLine();
char[] arr = str.ToCharArray();
int[] count = new int[10000];
for (int j = 0; j < arr.Length; j++)
{
if( arr[j] >= 'a' && arr[j] <= 'z' || arr[j] >= 'A'&& arr[j] <= 'Z' )
{
count[arr[j]]++;
}
}
int ans=0;
for (int j = 0; j < count.Length; j++)
{
if(count[j]>1)
{
ans++;
}
}
Console.Write("Number of duplicates: " + ans +" duplicates are: ");
for (int j = 0; j < count.Length; j++)
{
if(count[j]>1)
{
Console.Write((char)j +" " );
}
}
Console.WriteLine();
}
This Find to find Duplicates characters And Its Occurrence and I am using Key value pair in C#
/// <summary>
/// Find The Duplicates And Its Occurrence
/// </summary>
/// <param name="inputString"> input String for example
/// "Aassekoopannessyttoodde","Mississippi","raccoonnookkeeper"</param>
private static void FindTheDuplicatesAndItsOccurrence(string inputString)
{
// we used Dictionary to make this collection generic
Dictionary<Char, int> CharCount = new Dictionary<char, int>();
foreach (Char eachLetter in inputString)
{
if (eachLetter != ' ')
{
if (!CharCount.ContainsKey(eachLetter))
{
CharCount.Add(eachLetter, 1);
}
else
{
CharCount[eachLetter]++;
}
}
}
foreach (var item in CharCount)
{
if (item.Value > 1)
{
Console.WriteLine(item.Key + "," + item.Value);
}
}
}

can a string array go past 111?

I am trying to make an array that will gather all the lines in all the files in a directory, I thought I had it finally, but when the string array gets to entry 111 it crashes with an IndexOutOfRangeException
string[] WordList = new string[AdjectiveListLength];
Console.WriteLine("Length .. " + AdjectiveListLength);
Console.WriteLine("String Length .. " + WordList.Length);
int o = 0;
for (int i = 0; i < FileEntries.Length; i++)
{
WordList = File.ReadAllLines(FileEntries[i]);
foreach (string s in WordList)
{
Console.WriteLine(s + " .. " + i + " .. " + o);
WordList[o] = s;
//o += 1;
}
}
The exception points to the int I commented out when I get the error, I've been trying to get this for a few hours and I've finally gotten this far I feel like I'm 1 inch from the finish line but I can't figure out what's going on.
The best way for this task is to use a List<string> that could be used without knowing beforehand the length of each file in your FileEntries array
List<string> WordList = null;
for (int i = 0; i < FileEntries.Length; i++)
{
WordList = File.ReadLines(FileEntries[i]).ToList();
foreach (string s in WordList)
Console.WriteLine(s + " .. " + i);
// If you want also the line number then you could just use normal for..loop and C# 6.0 syntax
for(int o = 0; o < WordList.Count(); o++)
Console.WriteLine($"File:{i} at line {o} is ..{WordList[o]}");
}
If you really want to use arrays then you don't need to dimension the array because File.ReadAllLines already creates the array for you
string[] WordList = null;
for (int i = 0; i < FileEntries.Length; i++)
{
WordList = File.ReadAllLines(FileEntries[i]);
foreach (string s in WordList)
Console.WriteLine(s + " .. " + i);
}

C# - creating an array combination, need explanation

So here is my code:
Console.Write("Insert first array length: ");
string[] izmers1 = new string[Convert.ToInt32(Console.ReadLine())];
Console.Write("Insert second array length: ");
string[] izmers2 = new string[Convert.ToInt32(Console.ReadLine())];
for (int i = 0; i < izmers1.Length; i++)
{
Console.Write("Insert 1.array {0} array value: ", i + 1);
izmers1[i] = Console.ReadLine();
}
for (int j = 0; j < izmers2.Length; j++)
{
Console.Write("Insert 2.array {0} array value: ", j + 1);
izmers2[j] = Console.ReadLine();
}
for (int k = 0; k < izmers1.Length; k++)
{
Console.WriteLine("1.array {0} value is {1}", k + 1, izmers1[k]);
}
for (int p = 0; p < izmers2.Length; p++)
{
Console.WriteLine("2.array {0} value is {1}", p + 1, izmers2[p]);
}
I need to create a loop or something , that will create combination of array's.
Imagine we entered length 3 and 4.
Then insert some value for each, our output is:
1.array 1.value q
1.array 2.value w
1.array 3.value e
2.array 1.value Q
2.array 2.value W
2.array 3.value E
2.array 4.value R
i need to create a combination that will look like this one qQwWeER.
My english is not very good, so i hope someone understand what i need and can explain how to get it :)
You can use Linq's Enumerable.Range, Enumerable.Aggregate along with a StringBuilder to create the combined string:
var s = Enumerable.Range(0, Math.Max(izmers1.Length, izmers2.Length)).Aggregate(new StringBuilder(), (sb, i) =>
{
if (i < izmers1.Length) sb.Append(izmers1[i]);
if (i < izmers2.Length) sb.Append(izmers2[i]);
return sb;
}).ToString();
}
Update You need to learn to read Linq and lambda expressions, they are an integral part of the language and are used extensively. The code I wrote also could be rewritten as follows:
StringBuilder sb = new StringBuilder();
for (int i = 0, length = Math.Max(izmers1.Length, izmers2.Length); i < length; i++)
{
if (i < izmers1.Length) sb.Append(izmers1[i]);
if (i < izmers2.Length) sb.Append(izmers2[i]);
}
var s = sb.ToString();
This works too:
var result =
String.Join("", Enumerable.Zip(
izmers1.Concat(Enumerable.Repeat("", izmers2.Length)),
izmers2.Concat(Enumerable.Repeat("", izmers1.Length)),
(i1, i2) => i1 + i2));
It's worth learning some of these approaches as they can make your coding so much simpler.

Convert 2D float array into 1D array of strings

I have a 2D array of floats and I want to convert it into 1D array of strings, where each string is one row of elements from 2D array. I am not getting output in text file as I expected. Can anyone tell me what I'm doing wrong? It will be great help to me, if somebody could provide efficient code with corrections.
string[] set = new string[240];
string value = "#"
for (int i = 0; i < 240; i++)
{
for (int j = 0; j < 320; j++)
{
value = Convert.ToString(ImageArray[i, j]);
value += ",";
}
set[i] = value + Environment.NewLine;
value = " ";
}
for(int k=0;k<240;k++)
{
System.IO.File.AppendAllText(#"C:\Users\mtech\Desktop\sathya.txt", set[k]);
textBlock1.Text = set[k];
value = " ";
}
inside your inner for loop(j), you are overwriting the value of value variable.
i.e.
for (int j = 0; j < 320; j++)
{
value = Convert.ToString(ImageArray[i, j]);
value += ",";
}
instead of above, you should be doing:
for (int j = 0; j < 320; j++)
{
value += Convert.ToString(ImageArray[i, j]) +",";
}
also, you don't need to perform two nested loops for this task, take a look at String.Join
Here is the shorter way with LINQ:
var allValues = ImageArray.OfType<float>();
string[] lines = new string[240];
for(int i=0; i<240; i++)
{
lines[i] = string.Join(",", allValues.Skip(i*320).Take(320));
}
File.AppendAllLines(#"C:\Users\mtech\Desktop\sathya.txt", lines);
You're re-assigning value in every iteration in your nested for loop. Use the += operator, instead. Another thing you should consider is the use of StringBuilder if you're going to repeatedly append to a string. strings are immutable so you're actually creating a new string every time you append to it.
Not sure if this applies to your case (because of the boundaries in your for loops), but you can use LINQ to flatten a multidimensional array. Example:
float[,] arr = new float[2,2]
{
{123.48F, 45.3F},
{954.23F, 91.3F}
};
var str = string.Join("",
arr.Cast<float>()
.Select(x => Convert.ToString(x) + ","));

interview question - how to loop through an array with a different starting point?

Let's say you have the string "This is a test"
I pass it to method zee, like ("This is a test", 1)
and want "test This is a";
I pass it to method zee, like ("This is a test", 2)
and want "a test This is";
the number can exceed the total words in variable. If it does it should loop around.
I started with....
public static string zee(string origString, int i)
{
StringBuilder sb = new StringBuilder();
ArrayList list = new ArrayList();
list.AddRange(origString.Split(' '));
// not sure here -
for (int c = i; c < (list.Count + i); c++)
{
sb.AppendFormat("{0} ", list[c]);
}
return sb.ToString();
}
for(int j=0; j < list.length; j++){
int idx = (j + i) % list.length;
sb.AppendFormat("{0} " , list[idx]);
}
Mostly like Brent Arias's solution, but I think a for loop is more readable, less likely to go infinite.
public static string zee(string origString, int i)
{
StringBuilder sb = new StringBuilder();
List<string> list = new List<string>();
list.AddRange(origString.Split(' '));
for (int j = 0; j < list.Count; j++)
{
int idx = (j + i) % list.Count;
sb.AppendFormat("{0} ", list[idx]);
}
return sb.ToString();
}
This is how I'd solve it.
private static string f(string s, int start)
{
var arr=s.Split(' ');
start %= arr.Length;
var res=arr.Skip(arr.Length - start).ToList();
res.AddRange(arr.Take(arr.Length - start));
return string.Join(" ", res);
}
I tried writing a one liner with linq but I don't see how to combine 2 lists. Union and Join aren't what I need.
This is how I'd solve it using strings.
public static string zee(string origString, int i)
{
string[] splitStr = origString.Split(' ');
string newStr = "";
// Not sure what you meant by wrap around but this should
// do the trick.
i %= splitStr.Length;
for (int j = (splitStr.Length - i); j < splitStr.Length; j++)
newStr += splitStr[j] + " "; // Add spaces taken by split :(
for (int j = 0; j < (splitStr.Length - i); j++)
newStr += splitStr[j] + " ";
return
newStr;
}
Here's an abomination trying to cram as much into one line as possible:
static string zee(string sentence, int wordCount)
{
var words = sentence.Split(' ');
return string.Join(" ", new[] { words.Skip(words.Count() - wordCount), words.Take(words.Count() - wordCount) }.SelectMany(w => w).ToArray());
}
I havn't tried it, but I think this would do it:
i %= list.Length;
int index = i;
do {
index %= list.Length;
sb.AppendFormat("{0} ", list[index]);
while (++index != i);
static string rearrange(string phase,int index)
{
string[] words = phase.Split(' ');
string[] newwords = new string[words.Length];
int pointer = index;
for (int i = 0; i < words.Length;i++ )
{
if(pointer>=words.Length)
{
pointer = 0;
}
newwords[i] = words[pointer];
pointer++;
}
return string.Join(" ", newwords);
}
Sounds like a homework question to me, but here is an efficient use of the .Net framework:
private static string [] SplitWords(string s, int startWord)
{
string[] words = s.Split(' ');
List<string> output = new List<string>();
output.AddRange(words.Skip(startWord).ToArray());
output.AddRange(words.Take(startWord).ToArray());
return output.ToArray();
}
There is absolutely no error checking in this function so you will have to modify it for production code but you get the idea.
public string SetStart(int startAt)
{
const string sentence = "this is a test so it is";
var words = sentence.Split(' ');
var x = (startAt > words.Count()) ? startAt%words.Count() : startAt;
return string.Join(" ", words.Skip(x).Concat(words.Take(x)));
}

Categories

Resources