How can I display my results in C#? - c#

I have a program see below
I made the method but I want to display it in the console
and not on the easy way like console.writeline(str.length). I want using the method I made.
could someone help me please
thanks in advance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string str = "dit is een test 1,2,3";
Console.WriteLine(str);
}
public int CountAllNumbersAndChar(string str)
{
return str.Length;
}
}
}
Update:
I have the following program now
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string str = "this is a test 1,2,3";
int length = CountAllNumbersAndChar(str);
Console.WriteLine(str);
Console.WriteLine(length);// met de methode maar kan handiger met onderstaand voor beeld
// Console.WriteLine(str.Length);
// int numbers = str.Count(Char.IsNumber); // de makelijkste makelijke manier
//Console.WriteLine(numbers);
int countnumber = CountNumbers(str) ;
Console.WriteLine(countnumber);
int countwords = words(str);
Console.WriteLine(countwords);
}
public static int CountAllNumbersAndChar(string str)
{
return str.Length;
}
public static int CountNumbers(string str)
{
return str.Count(Char.IsNumber);
}
public static int words(string str)
{
int words = str.Split().Count(str => str.All(Char.IsLetter));
}
}
}
but it still doesnt work
could someone say me what I have to change ?

Is this what you want?
Console.WriteLine(CountAllNumbersAndChar(str));

Here's how you do it. Note public static int CountAllNumbersAndChar(string str) in the code below. You can't call CountAllNumbersAndChar from Main if you don't declare it as static.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string str = "this is a test 1,2,3";
int length = CountAllNumbersAndChar(str);
Console.WriteLine(length);
}
public static int CountAllNumbersAndChar(string str)
{
return str.Length;
}
}
}

You could use LINQ for all these tasks. Although I'm not sure you are familiar with it. It's really simple though, so have a look at the code and see if you can follow.
string str = "dit is een test 1,2,3";
// Length of the string
int chars = str.Length;
// LINQ: Count all characters that is a number
int numbers = str.Count(Char.IsNumber);
// LINQ: Split the string on whitespace and count the
// elements that contains only letters
int words = str.Split().Count(s => s.All(Char.IsLetter));
Console.WriteLine(chars); // -> 21
Console.WriteLine(numbers); // -> 3
Console.WriteLine(words); // -> 4
Of course, the way I'm counting words there is not perfect, but it should get you started. For more accurate ways you should google it as there are hundreds of examples out there.

I think you want to count number of numbers inside your string
public int CountAllNumbersAndChar(string str)
{
return str.Split(new char[]{' ',','},
StringSplitOptions.RemoveEmptyEntries).Count
(
x=>
{
int d;
return int.TryParse(x,out d);
}
);
}

Related

Formating a string (mask?)

I found that with long.Parse, ToString can take argument and I can format it to desired string, for example.
Input:
Console.WriteLine(long.Parse("123").ToString("#-#-#"));
Output:
1-2-3
I wanted to do something similar with string, lets say I wanna parse string to format ####-###-####. Is there any way to do it without regex with one liner like example above?
EDIT
Ok, so I may be misunderstood, I didn't want to parse numbers, but string instead. I can do in python like:
'{}-{}-{}'.format(*'abc') and I will receive a-b-c. In C# it seems to work only with numbers.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Text;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
Console.WriteLine("helloWorld".ToPhoneNumber("###-###-####"));
}
}
public static class AdvancedFormatString
{
public static string ToPhoneNumber(this string strArg, string outputformat)
{
if (outputformat == null)
return strArg;
var sb = new StringBuilder();
var i = 0;
foreach (var c in outputformat)
{
if (c == '#')
{
if (i < strArg.Length)
{
sb.Append(strArg[i]);
}
i++;
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
}
}

Factorial of a number not returning expected value

I'm trying to pass a test case as below:
using System;
using System.Collections.Generic;
using NUnit.Framework;
[TestFixture]
public class SolutionTests
{
[Test]
public void Test1()
{
var solution = new Solution();
Assert.AreEqual(solution.Factorial(5), 120);
}
}
My code is returning 3125 and the expected answer is 120.
My code is below and I'm not sure why it's not working.
using System;
using System.Collections.Generic;
using System.IO;
public class Solution
{
public int Factorial(int input)
{
int result = 1;
for (int i = 1; i <= input; i++)
{
result = result * input;
}
return result;
}
}
I have looked at other similar examples but I'm struggling to understand them due to my learning difficulties can someone please help
There is an error in Factorial function. You are using input instead of iterator. It should be rewritte like that:
using System;
using System.Collections.Generic;
using System.IO;
public class Solution
{
public int Factorial(int input)
{
int result = 1;
for (int i = 1; i <= input; i++)
{
result = result * i;
}
return result;
}
}
You should multiply the result on i and not on input in the for loop like this:
for (int i = 1; i <= input; i++)
{
result = result * i;
}

Convert upper cast to lower cast and Lower cast to upper cast in C#

using System;
using System.Numerics;
using System.Text;
class MyClass {
static void Main(string[] args) {
string str;
char[] str1=str.ToCharArray();
foreach (char c in inputArray)
{
if (char.IsLower(c))
str += char.ToUpper(c);
else
str += char.ToLower(c);
}
System.Console.WriteLine("str");
}
}
Error:tmp/CSHARP_30f1_944d_bf85_a405_1481953523/editor_source_509c_cad9_9662_9111_1481953523.cs(8,23): error CS0103: The name `inputArray' does not exist in the current context Compilation failed: 1 error(s), 0 warnings
Try this code , for performance you should use StringBuilder class :
using System.Text;
public class MyClass {
public static void Main(string[] args) {
string input="AbCdEf";
StringBuilder s1 = new StringBuilder();
foreach(char c in input){
if(char.IsLower(c)){
s1.Append(char.ToUpper(c));
}else{
s1.Append(char.ToLower(c));
}
}
System.Console.WriteLine(s1.ToString());
}
}
One line version using System.Linq
string input = "AAaaBBccDe";
var result = new String(input.Select(x => char.IsLower(x) ? char.ToUpper(x) : char.ToLower(x)).ToArray());

How to extract multiple numbers from the string?

I want to to extract multiple numbers from a string. The string may be like below:
hello:123.11,good:456,bye:789.78
And I want to get 3 numbers(including both integer and float numbers): 123.11, 456, 789.78 by C#.
Updated: including float number, not all integer.
How?
Thanks!
Try using Matches method of the Regex class with regex to get all the occurrence of the digits.
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var subjectString = "hello:123,good:456,bye:789";
var result = Regex.Matches(subjectString, #"[-+]?(\d*[.])?\d+");
foreach(var item in result)
{
Console.WriteLine(item);
}
}
}
DOT NET FIDDLE
using System.IO;
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string digitsOnly = String.Empty;
string s = "2323jh213j21h3j2k19hk";
List<int> MyNumbers = new List<int>();
foreach (char c in s)
{
if (c >= '0' && c <= '9') digitsOnly += c;
else
{
int NumberToSave;
bool IsIntValue = Int32.TryParse(digitsOnly, out NumberToSave);
if (IsIntValue)
{
MyNumbers.Add(Convert.ToInt16(digitsOnly));
}
digitsOnly=String.Empty;
}
}
foreach (int element in MyNumbers)
{
Console.WriteLine(element);
}
}
}

Pass data to nunit testcase

How pass data from the testrunner to the unittest?
For example an output path or interface configuration of the host machine?.
You may have already gone done a different path at tis point but I though I would share this. In post 2.5 versions of NUnit the ability to drive test cases in a via an external source was implemented. I did a demo of a simple example using a CSV file.
The CSV was something that contained my two test inputs and the expected result. So 1,1,2 for the first and so on.
CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace NunitDemo
{
public class AddTwoNumbers
{
private int _first;
private int _second;
public int AddTheNumbers(int first, int second)
{
_first = first;
_second = second;
return first + second;
}
}
[TestFixture]
public class AddTwoNumbersTest
{
[Test, TestCaseSource("GetMyTestData")]
public void AddTheNumbers_TestShell(int first, int second, int expectedOutput)
{
AddTwoNumbers addTwo = new AddTwoNumbers();
int actualValue = addTwo.AddTheNumbers(first, second);
Assert.AreEqual(expectedOutput, actualValue,
string.Format("AddTheNumbers_TestShell failed first: {0}, second {1}", first,second));
}
private IEnumerable<int[]> GetMyTestData()
{
using (var csv = new StreamReader("test-data.csv"))
{
string line;
while ((line = csv.ReadLine()) != null)
{
string[] values = line.Split(',');
int first = int.Parse(values[0]);
int second = int.Parse(values[1]);
int expectedOutput = int.Parse(values[2]);
yield return new[] { first, second, expectedOutput };
}
}
}
}
}
Then when you run it with the NUnit UI it looks like (I included a failure for example purposes:

Categories