Any utility to print out array directly? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an array, I am wondering any utility to print out array directly?

You can use string's Join() method, like this:
Console.WriteLine("My array: {0}",
string.Join(", ", myArray.Select(v => v.ToString()))
);
This will print array elements converted to string, separated by ", ".

You can use the following one liner to print an array
int[] array = new int[] { 1 , 2 , 3 , 4 };
Array.ForEach( array , x => Console.WriteLine(x) );

I like #dasblinkenlight solution, but I'd like to note that the select statement is not nessasary.
This code produces the same result for an array of strings:
string[] myArray = {"String 1", "String 2", "More strings"};
Console.WriteLine("My array: {0}", string.Join(", ", myArray));
I find it a little easier on the eyes having less code to read.
(linqpad is a fantastic app to test snippets of code like this.)

You can write an extension method something like this
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
var items = new []{ 1, 2, 3, 4, 5 };
items.PrintArray();
}
}
static class ArrayExtensions
{
public static void PrintArray<T>(this IEnumerable<T> elements)
{
foreach (var element in elements)
{
Console.WriteLine(element);
}
}
}
}

Related

Checking string value in a string using c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have following code in my project
var ReturnStr = Final_BOM.Tables[0].Rows[0]["NEW_BOM_IDS"].ToString();
the above line returns "12,13" but some times only "12"
var ReturnBOM = dsBOMDEfault.Tables[0].Rows[0]["Item_ID"].ToString();
the above line returns "14,15,13".
I want to check ReturnBOM values in ReturnStr
Can any one help how to check
You can use intersect:
Here a quick one-liner:
var results = ReturnStr.Split(',').Select(int.Parse)
.Intersect(ReturnBOM.Split(',').Select(int.Parse))
Demo:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var ReturnStr = "12,13";
var ReturnBOM = "14,15,13";
// Convert string to array with Split(',')
// if you dont want int just remove `.Select(int.Parse)`
var ReturnStrElements = ReturnStr.Split(',').Select(int.Parse);
var ReturnBOMElements = ReturnBOM.Split(',').Select(int.Parse);
// Keep only common elements
var results = ReturnStrElements.Intersect(ReturnBOMElements);
foreach(var item in results)
{
Console.WriteLine(item);
}
}
}
We use Split() to convert a string to an array where the delimiter is ','
[Optional] We use Select(int.Parse) to convert each element from string to int.
We use Intersect() to keep only common elements
Use LINQ.
using System.Linq;
The below code will give you an IEnumerable of String with the values you are looking for.
var inBoth = ReturnStr.Split(',').Intersect(ReturnBOM.Split(','))
You may then iterate through the values, cast them to Int32 or do whatever action you want.
If i understanded rights:
string[] returnBomVals = ReturnBom.Split(',');
string[] returnStrVals = ReturnStr.Split(',');
foreach (var vals in returnStrVals)
{
foreach (var strVals in returnBomVals)
{
if (ReturnStr.Equals(vals))
{
//Do Actions
}
}
}

How to unit test a console program that reads input and writes to the console [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Let's say I have a simple program like
using System;
public class Solution
{
public static void Main(string[] args)
{
int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
Array.Sort(arr);
Console.WriteLine(string.Join(" ", arr));
}
}
which I want to test in a separate project like
[TestMethod]
public void TwoNumbersDescendingAreSwapped()
{
string input = "2 1";
string expectedOutput = "1 2";
// ... ???
Assert.AreEqual(expectedOutput, actualOutput);
}
Is it possible to do that without actually using the .exe from Solution?
Move the code that does all the work in Main() to its own class and method:
public static class InputConverter
{
public static string ConvertInput(string input)
{
int[] arr = Array.ConvertAll(input.Split(' '), int.Parse);
Array.Sort(arr);
return string.Join(" ", arr);
}
}
Your Main() then becomes:
public static void Main(string[] args)
{
var input = Console.ReadLine();
var output = InputConverter.ConvertInput(input);
Console.WriteLine(output);
}
You can now test ConvertInput() without being dependent by the write and read functions of Console:
[TestMethod]
public void TwoNumbersDescendingAreSwapped()
{
// Arrange
var input = "2 1";
var expectedOutput = "1 2";
// Act
var actualOutput = InputConverter.ConvertInput(input);
// Assert
Assert.AreEqual(expectedOutput, actualOutput);
}
As an aside: the way you are passing in your arguments seems as though you are guaranteeing that the input will always be what you expect it to be. What happens when the user passes in something totally different than string representations of integers? You need to validate the input in InputConverter.ConvertInput() and create appropriate courses of action based on that (throw an Exception, return null, depends on what you're after). You'll then have to unit test those scenarios as well to make sure ConvertInput() performs as expected for all cases.

Get an array of string from a jagged array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a jagged array that contains other 1d string arrays:
string[] first = {"one","two"};
string[] second = {"three","four"};
string[][] jagged = {first,second};
When I try to get the sub-arrays, they give a null value (I might be doing something wrong):
foreach (string[] arr in jagged[][]) {
// My stuff here
}
Did I do something wrong in the array initialization progress or do I have to convert the sub-arrays somehow?
Just the foreach part is wrong.
I have tested it like as follows:
string[] first = { "one", "two" };
string[] second = {"three","four"};
string[][] jagged = {first,second};
foreach (string[] arr in jagged)
{
Console.WriteLine(string.Join(",", arr));
}
Output:
one, two
three, four
It should be:
foreach (string[] arr in jagged)
{
// My stuff here
}
I pasted your code on my local environment and could iterate just fine.
If you use jagged[][] in your loop, then possibly you get a type conversion failed message:
Cannot convert type 'char' to 'string'.
Instead use jagged in your loop.
public class Program
{
public static void Main()
{
string[] first = {"one","two"};
string[] second = {"three","four"};
string[][] jagged = {first,second};
foreach (string[] arr in jagged)
{
//Your code
}
}
}

Categorizing string based on input in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Title is like tl;dr version, here is what I mean:
I made currently just a string (to be a file with text), and I am splitting this string into separate words. I would like to make a method that allows me to mark words based on string/file. For example:
string nameOfString = "John likes pancakes";
Categorize(string nameOfString, class nameOfCategory)
this method would make John, likes and pancakes into a category (like Stupid, bestTexts) I passed to nameOfCategory.
I would like to count then the words into all of the categorys, so probably should use some kind of array top do this. Can someone help me with this? The big problem is I really have no idea how to pass the category (as a seperate class or just a string, maybe string[]?) and still be able to count it.
static void Main(string[] args)
{
var inputList = new List<string>
{
"John likes pancakes",
"John hates watching TV",
"I like my TV",
};
var dic = new Dictionary<string, int>();
inputList.ForEach(str => AddToDictionary(dic, str));
foreach (var entry in dic)
Console.WriteLine(entry.Key + ": " + entry.Value);
}
static void AddToDictionary(Dictionary<string, int> dictionary, string input)
{
input.Split(' ').ToList().ForEach(n =>
{
if (dictionary.ContainsKey(n))
dictionary[n]++;
else
dictionary.Add(n, 1);
});
}

text if a string has a word in it and display that string if it does in c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i want to have something like an "if" statement that tests a string for a word or a group of words.if the word(s) are in the string it displays the string on the console.
if anyone can help it would be much appreciated.
Though this is a terribly asked question; I'm going to go against my instincts and answer it.
Build a List<string> you want to search for:
private List<string> _words = new List<string> { "abc", "def", "ghi" };
then build a nice little extension method like this:
public static bool ContainsWords(this string s)
{
return _words.Any(w => s.Contains(w));
}
and so now you can just say:
myString.ContainsWords();
The entire extension class might look like this:
public static class Extensions
{
private List<string> _words = new List<string> { "abc", "def", "ghi" };
public static bool ContainsWords(this string s)
{
return _words.Any(w => s.Contains(w));
}
public static bool ContainsWords(this string s, List<string> words)
{
return words.Any(w => s.Contains(w));
}
}
NOTE: depending on the needs in your application, the second method is a lot more generic. It doesn't grab the list from the extensions class, but rather allows it to be injected. However, it could be that your application is so specific that the first approach is more appropriate.
Why not just use the .Contains() method....
string s = "i am a string!";
bool matched = s.Contains("am");
String [] words={"word1","word2","word3"};
String key="word2";
for(int i=0;i<words.Length;i++)
{
if(words[i].Contains(key))
Console.WriteLine(words[i]);
}
You can use String.Contains method like;
string s = "helloHellohi";
string[] array = new string[] { "hello", "Hello", "hi", "Hi", "hey", "Hey", "Hay", "hey" };
foreach (var item in array)
{
if(s.Contains(item))
Console.WriteLine(item);
}
Output will be;
hello
Hello
hi
Here a demonstration.

Categories

Resources