Hello guys, I don't need the answer but I would look to know and find out what I'm doing wrong. As a beginner I got a very "easy" assignment in my studies. I need to create a string and inside this string I need to replace some words by other words without using the for loop as so: ( also I want to print it but I got no clue where to put Console.WriteLine and google searching for 1 hour didn't work or asking a colleage.
/* Excersice: use with stringbuilder
* cat becomes littlecat
* dog becomes littledog
* mouse becomes littlemouse
* words the must be replace by a
* do not use a loop*/
using System;
using System.Collections.Generic;
using System.Text;
namespace Opgavens_leerpad_3_oefening
{
class Program
{
static string Main(string[] args)
{
StringBuilder sb = new StringBuilder();
string dogCat = new string("Can the cat find the mouse without waking the dog.");
static string replacethisstring(string dogCat);
{
hondKat = dogCat.Replace("cat", "littlecat");
hondKat = dogCat.Replace("dog", "littldog");
hondKat = dogCat.Replace("mouse", "littlemouse");
hondKat = dogCat.Replace("the", "a");
return dogCat;
}
}
}
}
Error CS5001: Program does not contain a static "Main" method suitable for an entry point ( I don't get this doesn't almost any program starts with this static Main args? )
Error CS8112: replacethisstring(string)' is a local function and must therefore always have a body. ( I just gave it a body right? I opened the { and close it } and put a replace with return. )
The method declaration ends with ; that’s the reason for CS8112
The Main method has to return void (or ‘int’ )you’ve modified it to string, that’s the reason for CS5001
If you want the program to print the output on the console use:
using System;
....
Console.WriteLine(output)
Your main should have a void as return type. string is not allowed but int is an option (see reference)
You cannot have ; at the end of a function declaration that has a body to it.
You have to declare a variable before you can use it ... string hondKat;
See the use of StringBuilder in the below code instead of string.
namespace Opgavens_leerpad_3_oefening
{
class Program
{
public static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append("Can the cat find the mouse without waking the dog.");
sb = replacethisstring(sb);
Console.WriteLine(sb.ToString());
Console.ReadLine(); // To Stop the Console from closing.
static StringBuilder replacethisstring(StringBuilder dogCat)
{
dogCat = dogCat.Replace("cat", "littlecat");
dogCat = dogCat.Replace("dog", "littldog");
dogCat = dogCat.Replace("mouse", "littlemouse");
dogCat = dogCat.Replace("the", "a");
return dogCat;
}
}
}
}
You can place the function within the Main or outside. Normally you would find functions outside of the Main class.
public static void Main(string[] args)
{
...
}
public static string replacethisstring(string dogCat)
{
...
}
Having several issues like typos, syntax error etc.
Additionally, the excercise having a condition that needs to use with stringbuilder.
So, try this.
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder("Can the cat find the mouse without waking the dog?");
sb = replacethisstring(sb);
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
static StringBuilder replacethisstring(StringBuilder dogCat)
{
StringBuilder hondKat = dogCat.Replace("cat", "littlecat");
hondKat = dogCat.Replace("the", "a");
hondKat = dogCat.Replace("dog", "littledog");
hondKat = dogCat.Replace("mouse", "littlemouse");
return hondKat;
}
Related
This is probably a simple fix, however I've spent a few hours trying to get this code to work. For my homework assignment, I have to open a text file and place it's data in an ArrayList. I did just that, but then I realized that I am required to do so but creating a method called ReadFileAndStoreInArrayList. Now here is where I am having trouble.
{
class Program
{
static void Main(string[] args)
{
*//This string variable "file" is saying it has been
//assigned but never used.*
string file = #"C:\Users\Latoy\Documents\Schoolwork\IT 232\Unit 5\FamousWords.txt";
}
*//Here is where I attempted to pass the variable by value*.
public void ReadFileAndStoreInArrayList(string file)
{
ArrayList FamousWords = new ArrayList();
using (StreamReader path = new StreamReader(file))
{
string line;
while ((line = path.ReadLine()) != null)
{
FamousWords.Add(line);
}
}
foreach (string line in FamousWords)
{
Console.Write(line);
}
}
}
}
I am fairly new to this, and I have done my research and still can not find what I am doing wrong. Is it the way I called the method? Note: The code works when placed in one method, however I am required to create a method. I attempted to use just the ReadFileAndStoreInArrayList method but the compiler is making me use the main method as well.
Use static keyword for the method you want to call from your main function, or else you won't be able to call it.
public static void ReadFileAndStoreInArrayList(string file)
{
ArrayList FamousWords = new ArrayList();
using (StreamReader path = new StreamReader(file))
{
string line;
while ((line = path.ReadLine()) != null)
{
FamousWords.Add(line);
}
}
foreach (string line in FamousWords)
{
Console.Write(line);
}
}
And then you can call it just like:
ReadFileAndStoreInArrayList(file);
in your main function which should look like:
static void Main(string[] args)
{
*//This string variable "file" is saying it has been
//assigned but never used.*
string file = #"C:\Users\Latoy\Documents\Schoolwork\IT 232\Unit 5\FamousWords.txt";
ReadFileAndStoreInArrayList(file);
}
You're not actually calling your method anywhere. You're missing a call to:
ReadFileAndStoreInArrayList(file);
In my last c# interview, I was asked to prove immutability of C# string,I know what is meant by immutability of c# string,But is it possible to prove immutability of c# string through code ? can i have a sample code snippet please.
Thanks in advance
I can prove that a string is not immutable. All I need to do is to show some code which mutates a string, like so:
using System;
using System.Runtime.InteropServices;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
const string test = "ABCDEF"; // Strings are immutable, right?
char[] chars = new StringToChar {str = test}.chr;
chars[0] = 'X';
// On an x32 release or debug build or on an x64 debug build,
// the following prints "XBCDEF".
// On an x64 release build, it prints "ABXDEF".
// In both cases, we have changed the contents of 'test' without using
// any 'unsafe' code...
Console.WriteLine(test);
// The following line is even more disturbing, since the constant
// string "ABCDEF" has been mutated too (because the interned 'constant' string was mutated).
Console.WriteLine("ABCDEF");
}
}
[StructLayout(LayoutKind.Explicit)]
public struct StringToChar
{
[FieldOffset(0)] public string str;
[FieldOffset(0)] public char[] chr;
}
}
Now whether this should be considered a bug in C# is a different matter. :)
(The answer is probably that FieldOffset should be considered to be unsafe - the code above is purportedly safe and therefore the string should not be mutatable.)
Also, I think you could legitimately argue that string is immutable in spirit, even if there are silly edge cases which violate its immutability in supposedly safe code.
Yes, It is possible to prove immutability of c# string using ObjectIDGenerator Class.
Following answer is taken from dotmob article on String Vs Stringbuilder in C#
Actually ObjectIDGenerator will return an unique integer value for instances that we created in our programs.With the help of this class we can check whether new instance is created or not for various operations on string and stringbuilder .Consider following program
using System;
using System.Text;
using System.Runtime.Serialization;
class Program
{
static void Main(string[] args)
{
ObjectIDGenerator idGenerator = new ObjectIDGenerator();
bool blStatus = new bool();
//just ignore this blStatus Now.
String str = "My first string was ";
Console.WriteLine("str = {0}", str);
Console.WriteLine("Instance Id : {0}", idGenerator.GetId(str, out blStatus));
//here blStatus get True for new instace otherwise it will be false
Console.WriteLine("this instance is new : {0}\n", blStatus);
str += "Hello World";
Console.WriteLine("str = {0}", str);
Console.WriteLine("Instance Id : {0}", idGenerator.GetId(str, out blStatus));
Console.WriteLine("this instance is new : {0}\n", blStatus);
//Now str="My first string was Hello World"
StringBuilder sbr = new StringBuilder("My Favourate Programming Font is ");
Console.WriteLine("sbr = {0}", sbr);
Console.WriteLine("Instance Id : {0}", idGenerator.GetId(sbr, out blStatus));
Console.WriteLine("this instance is new : {0}\n", blStatus);
sbr.Append("Inconsolata");
Console.WriteLine("sbr = {0}", sbr);
Console.WriteLine("Instance Id : {0}", idGenerator.GetId(sbr, out blStatus));
Console.WriteLine("this instance is new : {0}\n", blStatus);
//Now sbr="My Favourate Programming Font is Inconsolata"
Console.ReadKey();
}
}
Output Will look like this
Instance id for string get changed from 1 to 2 when str concatenated with “Hello World”.while instance id of sbr remains same as 3 after append operation also. This tells all about mutability and immutability. blStatus variable indicate whether the instance is new or not.
You can find complete article on the topic from : http://dotnetmob.com/csharp-article/difference-string-stringbuilder-c/
I am trying to make a program that will print whatever is after "print:" in a console application (I don't know how else to explain it)
If you don't understand I think my code will help you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteConsole
{
class Program
{
static void Main(string[] args)
{
while (true)
{
string input = Console.In.ReadLine();
char[] chars = input.ToCharArray();
if (input.Contains("print"))
{
int Place = 0;
int colenPlace = 0;
foreach (char a in chars)
{
Place++;
if (chars[Place].Equals(":"))
{
colenPlace = Place;
break;
}
}
Console.Write(input.Substring(colenPlace));
}
}
}
}
}
When I run the program and type "print:Hello World" it doesn't print "Hello World" like it should, it just goes to the next line.
At a quick glance I can see two bugs in your application:
First, if a ':' character is never found, the code will generate an IndexOutOfBoundsException. This is because you increment the index before you use it, so you're never comparing the first character of the input and will generate an exception after the last character. Move Place++; to the end of the loop to solve this:
foreach (char a in chars)
{
if (chars[Place].Equals(":"))
{
colenPlace = Place;
break;
}
Place++;
}
Second, this will never be true:
chars[Place].Equals(":")
The value is a char, but you're comparing it to a string. Compare it to a char instead:
chars[Place].Equals(':')
Or even just use a direct comparison (which should result in a compile-time error if you try to use a string by mistake):
chars(Place) == ':'
Could probably simplify it to:
static void Main(string[] args)
{
while (true)
{
var input = Console.ReadLine();
if input.StartsWith("print:")
Console.WriteLine(input.Replace("print:", ""));
}
}
I'm new to C#. I wrote a foreach loop,but how can I recall the variables outside the loop. Thanks for your help.
Here is my code:
static void Main(string[] args)
{
IDictionary<string,float> IDico=new Dictionary<string,float>();
IDico.Add("D1",1);
IDico.Add("D2",2);
IDico.Add("D3",3);
string tempo="D2";
foreach(var element in IDico.Keys)
{
if(tempo.Contains(element in IDico.Keys)
{
var outPut=IDico[element]
}
}
var call=outPut // How can I call outPut outside the for loop?Because the outPut doesn't exist for this row.
}
This is your code
static void Main(string[] args)
{
IDictionary<string,float> IDico=new Dictionary<string,float>();
IDico.Add("D1",1);
IDico.Add("D2",2);
IDico.Add("D3",3);
string tempo="D2";
float outPut = 0.0;
foreach(var element in IDico.Keys)
{
if(tempo.Contains(element))
{
outPut=IDico[element]
}
}
//Do stuff with outPut
}
however i think you may be trying to find tempo in the dictionary so really you should just do this:
static void Main(string[] args)
{
IDictionary<string,float> IDico=new Dictionary<string,float>();
IDico.Add("D1",1);
IDico.Add("D2",2);
IDico.Add("D3",3);
string tempo="D2";
float outPut = 0.0;
if(IDico.Contains(tempo))
{
outPut=IDico[tempo];
}
//Do stuff with outPut
}
static void Main(string[] args)
{
IDictionary<string,float> IDico=new Dictionary<string,float>();
IDico.Add("D1",1);
IDico.Add("D2",2);
IDico.Add("D3",3);
string tempo="D2";
string outPut = string.Empty;
foreach(var element in IDico.Keys)
{
if(tempo.Contains(element))
{
outPut = IDico[element]
}
}
var call = outPut;
}
If outPut can contain more than one element from your dictionary consider using and array or list. If you want to stop iterating after you find a match use a break; in the if statement so that after the match is found the loop will stop.
Also, you're going to want to declare outPut outside of loop so it doesn't re declare itself on each iteration of the loop.
I also fixed the contains statement for you as well as you were using improper syntax.
I have a console program, I'd like to continuously mirror the result of Console.Write to a collection, which I can look at the tail of in real time. The collection could be an array, a list, etc.
I assume I'd have to use some sort of event handler?
I don't mind being pointed in the direction of a 3rd party library, e.g. NLog.
Update
I need to maintain a collection in memory, which mirrors the current console state (I can then send to a remote WinForms app using sockets). Details aside, I think I can do this with a few lines of C# - I don't want to add a huge logging library without a good need for it.
The Console class allows you to replace the output and error streams. Just what you need here, you can replace them with a TextWriter that also logs what is written. A sample implementation:
class ConsoleLogger : System.IO.TextWriter {
private System.IO.TextWriter oldOut;
private Queue<string> log = new Queue<string>();
private StringBuilder line = new StringBuilder();
private object locker = new object();
private int newline;
private int logmax;
public ConsoleLogger(int history) {
logmax = history;
oldOut = Console.Out;
Console.SetOut(this);
}
public override Encoding Encoding {
get { return oldOut.Encoding; }
}
public override void Write(char value) {
oldOut.Write(value);
lock (locker) {
if (value == '\r') newline++;
else if (value == '\n') {
log.Enqueue(line.ToString());
if (log.Count > logmax) log.Dequeue();
line.Length = newline = 0;
}
else {
for (; newline > 0; newline--) line.Append('\r');
line.Append(value);
}
}
}
}
Usage:
static void Main(string[] args) {
var outLogger = new ConsoleLogger(100);
// etc...
}
You could probably write a new TextWriter who's Write calls populate a list instead of writing to a stream. You would then need to set this through Console.SetOut(...)
Using Console.SetOut you can set your custom implemented TextWriter.
You can create a simple helper method and call that instead of Console.Write.
private void WriteToConsole(string message)
{
myList.Add(message);
Console.Write(message);
}
If you want to write code like:
WriteToConsole("{0} tel is: {1:+### ### ### ###}", "Name", 242352356578);
Then you could have code:
private static Queue<String> q = new Queue<String>(1000);
private static void WriteToConsole(String message)
{
q.Enqueue(message);
Console.Write(message);
}
private static void WriteToConsole(String message, params Object[] r)
{
String s = String.Format(message, r);
q.Enqueue(s);
Console.Write(s);
}
Use log4net for continuosly dump in the file, and then use this for tail: http://tailf.codeplex.com/
See Capturing console output from a .NET application (C#).