changing string dynamically in C# - c#

When I'm putting the following code specifically in the immediate window in Visual studio, it returns correctly:
whatToMatch.Remove((whatToMatch.IndexOf(input[i])), 1)
But when I put it in a program as shown below, it fails:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IsPangram
{
class Program
{
static void Main(string[] args)
{
string whatToMatch = "abcdefghijklmnopqrstuvwxyz";
string input = Console.ReadLine().ToLower();
for (int i = 0; i < input.Length; i++)
{
if (whatToMatch.Contains(input[i]))
{
whatToMatch.Remove((whatToMatch.IndexOf(input[i])), 1);
}
if (whatToMatch.Length == 0)
Console.WriteLine("pangram");
}
Console.WriteLine("not pangram");
}
}
}
I was expecting "whatToMatch" to change dynamically as it is correct code, but it's not changing. Why? And how to resolve this issue?

From msdn about String.Remove Method (Int32, Int32)
It returns a new string in which a specified number of characters in
the current instance beginning at a specified position have been
deleted.
So it doesn't modify the string that call it, it return a new string.
So you should use
whatToMatch = whatToMatch.Remove((whatToMatch.IndexOf(input[i])), 1)

As already mentioned, strings in .NET are immutable, therefore you cannot expect your string to change dynamically.
Here is a concise solution to your problem using LINQ:
using System;
using System.Collections.Generic;
using System.Linq;
namespace IsPangram
{
static class Program
{
public static bool IsPangram(this string input)
{
return
!input.ToLower()
.Aggregate("abcdefghijklmnopqrstuvwxyz".ToList(),
(ts, c) => ts.Where(x => x != c).ToList())
.Any();
}
public static void Main(string[] args)
{
Console.WriteLine(Console.ReadLine().IsPangram() ?
"Is pangram" :
"Is not pangram");
}
}
}

Related

Class Values passing in C# [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 5 years ago.
Improve this question
I have 2 classes, 1 is creating a string of random characters and the the other class is used to test if the function is working. When i run the Tester class however im getting a blank screen? Im very new to C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class FileNamer
{
public string GetFullName()
{
const string pool = "abcdefghijklmnopqrstuvwxyz0123456789";
var builder = new StringBuilder();
Random rd = new Random();
for (var i = 0; i < 26; i++)
{
var c = pool[rd.Next(0, pool.Length)];
builder.Append(c);
}
return builder.ToString();
}
}
}
And my Tester class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Tester
{
public string mytest()
{
FileNamer fn = new FileNamer();
Console.WriteLine(fn.GetFullName());
return "a";
}
}
}
I have rewritten your code in my side. It perfectly works.
My Main() method inside Program class is as follows:
class Program
{
static void Main(string[] args)
{
Tester aTester = new Tester();
aTester.mytest();
Console.ReadKey();
}
}
When I have run it twice. 1st time, it has shown: rfg67i87lmwfks337k8znpx7uk
. 2nd time, the output is: l5d68178ez5t52hx0bqq97us0o

Printing the letters from A-Z using recursion in c#

So here's what I have so for, I'm trying to print all the numbers from A-Z but it only prints Z, please help and thanks (using recursion)
using system;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace AtoZRecursion
{
class Program
{
static void Main(string[] args)
{
int number=65;
getAplha(number);
Console.WriteLine(Convert.ToChar(getAplha(number)));
Console.ReadKey();
}
public static int getAplha(int number=65)
{
if (number==90)
{
return Convert.ToChar(number);
}
return Convert.ToChar(getAplha(number + 1));
}
}
}
Remove the WriteLine from Main and put it just at the start of getAlpha, so that every letter is printed, as there is a call for each letter.
You can change the return type of your method and invoke it like Console.WriteLine(getAplha(65));
public static string getAplha(int number = 65)
{
if (number == 90)
{
return "" + (char)number;
}
return (char)number + getAplha(number + 1);
}
The WriteLine only happens once, when you "pop" back from the deepest recursion level.
You need to write from the getAlpha method.
You are only logging the last value of the recursion in Console.WriteLine. Instead, wrap your WriteLine like this:
using system;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace AtoZRecursion
{
class Program
{
static void Main(string[] args)
{
int number=65;
getAplha(number);
Console.ReadKey();
}
public static int getAplha(int number=65)
{
if (number==90)
{
Console.WriteLine(Convert.ToChar(number));
return Convert.ToChar(number);
}
Console.WriteLine(Convert.ToChar(number));
return Convert.ToChar(getAplha(number + 1));
}
}
}
For this to work you need the Console.WriteLine inside of the recursive method
public static void getAplha(int number=65)
{
Console.WriteLine(Convert.ToChar(number));
if (number==90)
{
return;
}
getAplha(number + 1);
}
And then you don't need a return type.

C# help, can't get list of names from 4 loops

Im trying to learn the 4 types of loops, for, foreach, while and do. I've made this code so far:
Loops.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LoopFrame
{
class Loops
{
// attribute (not property)
private List<string> names;
// constructor
public Loops()
{
// initilize
names = new List<string>();
//insert values
names.Add("Peter");
names.Add("Susanne");
names.Add("Steen");
names.Add("Mohammed");
names.Add("Poul");
names.Add("Ebbe");
names.Add("Henrik");
names.Add("Per");
names.Add("Anders");
names.Add("Lars");
names.Add("Vibeke");
names.Add("Mogens");
names.Add("Michael");
}
//
// 4 loop methods
//
// all should print out the whole list 'names'
//
public void WhileLoop()
{
int x = 0;
while (x < names.Count)
{
Console.WriteLine(names[++x]);
}
}
public void DoWhileLoop()
{
int x = 0;
do
{
Console.WriteLine(names[++x]);
x++;
} while (x < names.Count);
}
public void ForLoop()
{
for (int x = 0; x < 0; x++)
{
Console.WriteLine(names[++x]);
}
}
public void ForeachLoop()
{
int[] names = new int[] { 0 };
foreach (int element in names)
{
System.Console.WriteLine(element);
}
System.Console.WriteLine();
}
}
}
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LoopFrame
{
class Program
{
static void Main(string[] args)
{
Loops loops = new Loops();
Console.WriteLine();
Console.ReadLine();
}
}
}
I think there is some faults, but the program can currently compile, but it just makes a black screen.
Thank you for your time.
As it stands, you're constructing the Loops instance, but you've not called any methods.
static void Main(string[] args)
{
Loops loops = new Loops();
loops.WhileLoop();
loops.DoWhileLoop();
loops.ForLoop();
loops.ForeachLoop();
Console.WriteLine();
Console.ReadLine();
}
You may want to read up on Methods.
As an aside, you can populate your list with much less code:
names = new List<string> { "Peter", "Suzanne", "Steen" ... };
As another aside, in two of your loop methods, you're incrementing the index variable twice per iteration, which should only print out every other element.
You are not calling any method that should print the list content.
Add:
static void Main(string[] args)
{
Loops loops = new Loops();
//Call methods
loops.WhileLoop();
loops.DoWhileLoop();
//...
Console.WriteLine();
Console.ReadLine();
}
Your foreach will not work. As you declared a new names as int[]. To make your foreach workable with declared list. You should use
foreach(string s in names)
{
Console.WriteLine("Name is : "+s);
}

Error missing namespace or assembly reference

I am writing the code right, but getting error - missing namespace or assembly reference.Is there something wrong with the code or I am missing something?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
int i = 0;
int sum = 0;
int[] arr = new int[] { 1, 2 };
do
{
{
sum += arr[1];
Console.WriteLine("Wow");
i++;
}
}
while (i < 3);
}
}
}
Error is : Error Cannot initialize type 'int' with a collection initializer because it does not implement 'System.Collections.IEnumerable
My namespace ended in Console (i.e. MyProject.Console) which messed up the calls to Console.Write. In this case, either write the fully qualified name System.Console.Write or change the namespace.
i am writing the code right
Don't start with this assumption. Always start with the assumption that the compiler is correct, and your code is wrong.
You haven't shown any using directives. In this case all you need is
using System;
(Either at the very top of your code or within the namespace declaration.)
or change your WriteLine call to:
System.Console.WriteLine("Wow");
If that doesn't fix it (or if you've already got such a using directive but forgot to include it), then your project is probably somewhat broken - it's not like you're using any exotic types.
Import the System namespace or just use System.Console.WriteLine("...");
using System;
namespace TestNs
{
public class Test
{
static void Main()
{
Console.WriteLine("Hello World");
}
}
}
I faced a similar problem. The namespace name I used ended with .Console, so there was a conflict with System.Console
using System;
namespace Test.Console
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
I changed Test.Console to Test.ConsoleApp, and problem fixed for me
using System;
namespace Test.ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
The minimum for your console app should have this
using System;
using System.Collections.Generic;
using System.Text;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
}
}
}
thanks to all for help i managed to solve the problem with the help of you guys :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
int i = 0; //initialize integer i=0
int sum = 0; // initialize integer sum = 0;
int[] arr = new int[]{1, 2, 3, 4}; // array containing 4 integers elements
do
{
{
sum+=arr[i]; //sum each integer in array and store it in var sum
i++; //increment i for each element of array
Console.WriteLine(sum); //output the var sum conatining values after each increment
}
}
while(i<=3); //check condition for number of elements in array
}
}
}
Using a namespace of Myproject.App also causes problems, in the same way as MyProject.Console (as per contactmatt's answer, above).

Input string was not in a correct format. Converting String to double

I'm quite a beginner in C# , empty string to double conversion can be carried out under the button1_click event ..but doing it under Public Form1() it gives me this error
Input string was not in a correct
format.
Here`s the code..(the form1.cs and the Guy.cs class)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
guy1 = new Guy() ;
guy1.guyname = textBox1.Text;
guy1.guycash = double.Parse(textBox2.Text);
}
}
Guy guy1 ;
private void button1_Click(object sender, EventArgs e)
{
label5.Text = guy1.TakeCash(double.Parse(textBox3.Text)).ToString();
}
}
}
The Guy.cs Code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class Guy
{
private string name;
private double cash;
public string guyname
{
get { return name; }
set { name = value; }
}
public double guycash
{
get { return cash ; }
set { cash = value; }
}
public double TakeCash(double amount)
{
if (cash > amount)
{
cash -= amount;
return cash;
}
else
{
MessageBox.Show("Not enough Cash.");
return 0;
}
}
}
}
the error is caused by the guy1.guycash = double.Parse(textBox2.Text); line , when i try double.TryParse(textbox2.Text, out x) in If() before it, it returns false .
how to solve this please ?
thanks in advance .
Continuing from astanders answer:
double d;
if(!Double.TryParse(textBox2.Text, out d)){
return; // or alert, or whatever.
}
guy1 = new Guy() ;
guy1.guyname = textBox1.Text;
guy1.guycash = d;
What you're doing is attempting the parse, and if it fails, taking some other action. Since the user can input anything they want, this guarantees that if you fail to parse the input (because it's not a decimal), you can handle it nicely and tell them to fix their input.
This should be fine
double d;
Double.TryParse(String.Empty, out d);
Double.TryParse Method (String, Double%)
It looks like the problem is that you are not handling inproper user input. You are trying to parse string from textbox to double without suggestion that it may not be parsed ok (for example user could input 'abcd' in the textbox). Your code should use TryParse method and show error message when input was not parsed.
I guess parsing fails because of non-numeric input or becase of culture problems (like you have "." as desimal symbol by user inputs number with ",").

Categories

Resources