what is the purpose of Specific line in the Code - c#

i am reading a book named "Visual C# 2012 Programming" and i came up with following code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ch05StringManupulationEx
{
class Program
{
static void Main(string[] args)
{
string myString = "String with small s";
char[] myChar = myString.ToCharArray();
foreach (char whatever in myString)
{
Console.WriteLine("{0}", whatever);
}
Console.Write("\nyou have entered {0} characters in String ",myString.Length);
Console.ReadKey();
}
}
}
i don't know what the aurthor is doing on line :
char[] myChar = myString.ToCharArray();
because he is not using the variable named myChar anywhere in the code and even though i commented the line and compiled the program the output is same, can any one explain what is the purpose of this line in this code ?

Probably they forgot to remove that line or show what does it do, It's an array of character, A string is full of characters, each letter of a string is a character, you can access any of these arrays by using a zero based numbers, for example:
string a = "Hello";
// Prints e
Console.WriteLine(a[2]);
You can change this line to myChar to understand, It's same to an array of string, Which means a string is an array of chars, here's the example:
foreach (char whatever in myChar)
{
Console.WriteLine("{0}", whatever);
}

Related

Replacing a string with an equal amount of underscores

I'm trying to replace all characters of a string with underscores. From my readings a string is ordinarily immutable which means it cannot be modified superficially once it has been created.
I've decided to use StringBuilder to carry out the modification, though I need the underscores to be for display purposes only (hangman game) and not actually alter the value.
I've read through the Microsoft docs and feel like I'm doing the right thing but cannot understand why it won't work. Code below.
using System;
using System.Text;
namespace randomtesting
{
internal class Program
{
static void Main(string[] args)
{
string str = "hello";
StringBuilder sb = new StringBuilder(str);
sb.Replace(str, "_", 0, str.Length);
Console.WriteLine(str);
}
}
}
Edit -
What I ended up doing to get it to do what I wanted - unsure if ideal. Please provide feedback if there's a better way to do it, feel like it's not the most efficient way, but it works.
using System;
using System.Text;
namespace randomtesting
{
internal class Program
{
static void Main(string[] args)
{
string str = "hello";
string strDisplayedAsUnderscores = new string('_', str.Length);
Console.WriteLine(strDisplayedAsUnderscores);
char guess = Convert.ToChar(Console.ReadLine().ToLower()); //reads the user's guess
int guessIndex = str.IndexOf(guess); //gets the index of the character guessed in relation to the original word
StringBuilder word = new StringBuilder(strDisplayedAsUnderscores); //converts the underscores into a StringBuilder string
if (str.Contains(guess))
{
Console.WriteLine(word.Replace('_', guess, guessIndex, 1));
//if guess is contained in the original word
//replace the indexed underscore with the
//guessed character
}
}
}
}
You want this System.String constructor
string result = new string('_', str.Length);

regex pattern for the following string Amby : Dexter,Dexter : Karla

I have a input list that takes input in the above format and put them into a comma seperated string. I would like to get strings before and after colon(:).
I tried this regex pattern
string[] reg = Regex.Split(x, #"^(?:[\w ]\:\s[\w]+)+$");
but it doesnt seem to work. Please help.
Below is my code. This is a C# console application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace test
{
class Program
{
static void Main(string[] args)
{
List<string> input = new List<string>();
Console.WriteLine("Please enter your input");
string readinput = Console.ReadLine();
input.Add(readinput);
while (readinput != "")
{
readinput = Console.ReadLine();
input.Add(readinput);
}
string x = string.Join(",", input.ToArray());
Console.WriteLine(x);
// using regex
string[] reg = Regex.Split(x, #"^(?:[\w ]\:\s[\w]+)+$");
Console.WriteLine(reg);
Console.ReadLine();
}
}
}
Sorry i was not very clear but the
input : Amby : Dexter,
Dexter : Karla,
Karla : Matt .....
Expected Output is Amby, Dexter, Karla, matt....
If I understood you correctly... User enters some strings, and then you join them with commas. After that you want to split that string by colons?
Why don't you use simpler solution like this:
string[] reg = x.Split(':').Select(s => s.Trim()).ToArray();
Maybe this will get you started:
new Regex(#"(([a-zA-Z])+(?:[\s\:\,]+))").Matches("...");
or this regex
"\b([a-zA-Z])+\b"
Iterate over the MatchCollection.

need to do an ascii shift cypher in c#

I am trying to shift the characters in a string by 20 to match a file format I used in basic. I am using the following code in c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test_controls
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string text3;
private void button1_Click(object sender, EventArgs e)
{
// This is a test conversion of my pdw save routine from basic to c#
int pos = 0;
string text = label1.Text;
int t = text.Length; // get the length of the text
while (pos < t + 1) ;
string s = text.Substring(pos, 1); // get subsstring 1 character at a time
byte[] ASCIIValues = Encoding.ASCII.GetBytes(text); // convert that character to ascii
foreach (byte b in ASCIIValues)
{
int temp = b;
temp = temp + 20; // add 20 to the ascii value
char text2 = Convert.ToChar(temp); // convert the acii back into a char
text3 =""+ text2.ToString(); // add the char to the final string
}
label1.Text = text3; // rewrite the new string to replace the old one for the label1.text
}
}
}
The problem is it just does nothing and doesn't respond and I have to tell windows to close the unresponsive program. To be clear, I'm using winforms in c# to make a shift cypher. All of this code I'm using I found in various answers and pieced it together. in Vb or any other basic, I would just get the ascii value of each character in the string then do the math and convert it back using the chr$ command.
Any help would be greatly appreciated.
You have two problems. As pointed out in the comments, the following line is an infinite loop:
while (pos < t + 1) ;
Even without the loop, though, your shift algorithm is incorrect. The following line will also lead to incorrect results:
temp = temp + 20;
Consider as counterexamples the following cases:
G maps to [
ASCII z = 122. 122 + 20 = 144, which isn't even a valid ASCII character.
Uppercase Z would map to lowercase n
You could come up with other similar cases.
Incidentally, you could also rewrite this line as temp += 20.
Finally, this line is incorrect:
text3 =""+ text2.ToString();
You're not appending the new text to text3, you're replacing it every time you do an iteration, so text3 will always contain the last character encoded (rather than the entire string). Keep in mind, too, that building a C# string like this (especially a long one) is inefficient as strings are immutable objects in C#. If the string in question might be long you want to consider using a StringBuilder for this purpose.

Extracting and reading decimal numbers from a string in C#

I am relatively new to C# programming and I apologize if this is a simple matter, but I need help with something.
I need a function which will 'extract' regular AND decimal numbers from a string and place them in an array. I'm familiar with
string[] extractData = Regex.Split(someInput, #"\D+")
but that only takes out integers. If I have a string "19 something 58" it will take 19 and 58 and store them into two different array fields. However if I had "19.58 something" it will again take them as two separate numbers, while I want to register it as one decimal number.
Is there a way to make it 'read' such numbers as one decimal number, using Regex or some other method?
Thanks in advance.
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication9
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string[] inputs = {
"9 something 58" ,
"19.58 something"
};
foreach (string input in inputs)
{
MatchCollection matches = Regex.Matches(input, #"(?'number'\d*\.\d*)|(?'number'\d+[^\.])");
foreach (Match match in matches)
{
Console.WriteLine("Number : {0}", match.Groups["number"].Value);
}
}
Console.ReadLine();
}
}
}
Try this
Regex.Replace(someInput, "[^-?\d+\.]", ""))

Attempting to convert a char array to a string and then comparing length

My char[] both consist of exactly one element. My job is to compare the length of the element of the first array to the one of the second.
using System;
using System.Linq;
namespace FirstLecture
{
class Program
{
static void Main(string[] args)
{
char[] ints = {char.Parse(Console.ReadLine())};
char[] ints2 = {char.Parse(Console.ReadLine())};
string s1 = new string(ints);
string s2 = new string(ints2);
if (s1.Length > s2.Length)
{
Console.WriteLine(">");
}
else if (s1.Length < s2.Length)
{
Console.WriteLine("<");
}
else {
Console.WriteLine("=");
}
}
}
}
When I run the program in the console, I get String must be exactly one character long. I'm assuming there is some sort of a data type conversion error, cannot pin point it. Is this the case?
char.Parse only parses one single character, not the entire string you read from Console.ReadLine (so if you just type 'A' in your console, it should work).
Instead, you could just assign the string to the character array:
char[] ints = Console.ReadLine().ToArray();
It seems useless though since you immediate after assigning the characters construct a string out of it again. Both input and resulting strings should be the same.
This should be okay:
string s1 = Console.ReadLine();

Categories

Resources