Replace 4 different characters - c#

I'm trying to take the user input, E.G. ATCG and replace the letters with TAGC. These are DNA Complementary Bases. For example, if the user was to enter ATCGGGC it would output TAGCCCG. I've managed to replace 1 character, but I'm not sure how to get the others to replace.
namespace DNA_Replication_EASY
{
class Program
{
static string input1;
public static string InputBaseWithSpaces()
{
return string.Join(" ", input1.ToCharArray());
}
public static string OpposingBases()
{
string outputBases1 = input1.Replace("A", "T");
return outputBases1;
}
static void Main(string[] args)
{
Console.WriteLine("Please type out your DNA strand bases E.g. A T C G C A T G");
input1 = Console.ReadLine();
Console.WriteLine(InputBaseWithSpaces());
Console.WriteLine(OpposingBases());
Console.ReadLine();
}
}
}

Use Regex.Replace to replace string based on a dictionary (map):
Dictionary<string, string> complementary = new Dictionary<string,string>()
{
{ "A", "T" },
{ "T", "A" },
{ "C", "G" },
{ "G", "C" }
};
string input = "ATCG";
string result = Regex.Replace(input, "[ATCG]", match => complementary[match.Value]);
this replaces any of the "ATCG" character match with corresponding value from dictionary.

string MakeOpposite(string sourceString) {
var opposites = new Dictionary<char, char> {
{ 'A', 'T' },
{ 'T', 'A' },
{ 'G', 'C' },
{ 'C', 'G' }
};
var oppositeString = new string(sourceString.Select(x => opposites[x]));
return oppositeString;
}

Convert it to a char array and replace in place
string input = "ATCG";
//TAGC
char[] inputChar = input.ToCharArray();
for(int i=0;i< inputChar.Length; i++)
{
switch(inputChar[i])
{
case 'A':
inputChar[i]='T';
break;
case 'T':
inputChar[i]='A';
break;
case 'G':
inputChar[i]='C';
break;
case 'C':
inputChar[i]='G';
break;
}
}
var output =new string(inputChar);

I would use a foreach and switch statement over your Char Array to replace each letter.
foreach (char base in strand)
{
switch (base.ToString())
{
case "g":
//replace code
break;
case "c":
//replace code
break;
}
}

You should instead write a routine to go through character by character and do the replacement (don't use the string.replace method).
private string ConvertDNA(string original)
{
StringBuilder newone = new StringBuilder();
foreach(char c in original)
{
switch(c)
{
case 'A':
newone.Append('T');
break;
case 'T':
newone.Append('A');
break;
case 'C':
newone.Append('G');
break;
case 'G':
newone.Append('C');
break;
default:
newone.Append(c);
break;
}
}
return newone.ToString();
}
Note that if your original string is certain forms of Unicode, this could do funny things. You should use stringbuilder rather than the += syntax in the other answers because its more efficient.

One way to do it is by using a Switch statement
public static string OpposingBases()
{
string outputBases1;
foreach(var s in input1)
{
switch (s)
{
case "A":
outputBases1 +="T";
break;
case "T":
outputBases1 +="A";
break;
case "C":
outputBases1 +="G";
break;
case "G":
outputBases1 +="C";
break;
case " ":
outputBases1 +=" ";
break;
default:
break;
}
}
return outputBases1;
}

Simple solution, but you can do better:
code = code.Replace("A","x").Replace("C","y").Replace("T","A").Replace("G","C").Replace("x","T").Replace("y","G");

You could do this
public static string OpposingBases()
{
var baseDictionary = new Dictionary<char, char>()
{
{'A', 'T'},
{'T', 'A'},
{'C', 'G'},
{'G', 'C'}
};
return input1.Where(baseDictionary.ContainsKey).Aggregate("", (current, c) => current + baseDictionary[c]);
}

Related

How to get the month name using Dictionary in C#?

I have implemented the first three letters of the month to full name of the month in get Full Month function it is returned based on three letters .
But how to implemented in Dictionary concept Any one simplify modify this code given below code:
**public static string getFullMonth(string mthname)
{
string Mthname = "";
switch (mthname.ToUpper())
{
case "JAN":
Mthname ="January";
break;
case "FEB":
Mthname = "February";
break;
case "MAR":
Mthname = "March";
break;
case "APR:":
Mthname = "April";
break;
case "MAY":
Mthname = "May";
break;
case "JUN":
Mthname = "June";
break;
case "JUL":
Mthname = "July";
break;
case "AUG":
Mthname = "August";
break;
case "SEP":
Mthname = "September";
break;
case "OCT":
Mthname = "October";
break;
case "NOV":
Mthname = "November";
break;
case "DEC":
Mthname = "December";
break;
default:
Console.WriteLine("Invalid grade");
break;
}
return Mthname;
}**
simplify this code given below code
Yes, don't use a dictionary at all:
public static string GetFullMonth(string englishShortMonthName)
{
CultureInfo englishCulture = CultureInfo.InvariantCulture;
if (DateTime.TryParseExact(englishShortMonthName, "MMM", englishCulture, DateTimeStyles.None, out DateTime dt))
return dt.ToString("MMMM", englishCulture);
return englishShortMonthName;
}
Read about the month ("M", "m") format specifier
Look up Dictionary syntax. Ultimately you're looking for something like this:
var monthNames = new Dictionary<string, string>
{
{ "JAN", "January" },
{ "FEB", "February" },
...
}
Please find complete solution
public static string getFullMonth(string mthname)
{
var monthNames = new Dictionary<string, string>
{
{ "JAN", "January" },
{ "FEB", "February" },
...
}
return monthNames[mthname];
}
But above code looks weird So You should create dictionary globally and initialize in constructor.
Add only below line in getFullMonth function.
return monthNames[mthname];

How to get all the values within multiple curly braces

How do I split the following into an array of strings within the curly braces?
i have tried regex, but the pattern is thrown off because of the new line
string script = #"{
ABC
DEF
}
{
GHI
LMN
}
{
QWE
ERT
}
"
return an array of with the new line intact
["ABC\nDEF", "GHI\nLMN", "QWE\nERT"]
Hej i hope i got you right.
I know it is not the nices solution but it is something.
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp6
{
internal class Program
{
private enum Token
{
Open,
Close,
Char,
UnKnowChar,
Space,
NewLine,
}
private static void Main(string[] args)
{
var text = #"{
ABC
DEF
}
{
GHI
LMN
}
{
QWE
ERT
}
";
var strings = Parse(text).ToArray();
}
private static IEnumerable<string> Parse(string text)
{
var strings = new List<string>();
var tokens = GetTokens(text);
var opens = tokens.Select((token, index) => new {token, index})
.Where(list => list.token == Token.Open).ToList();
foreach (var open in opens)
{
var index = tokens.FindIndex(open.index, token => token == Token.Close);
var substring = text.Substring(open.index + 1, index - open.index - 1);
var trim = substring.Trim('\r', '\n', ' ');
strings.Add(trim.Replace(' '.ToString(), string.Empty));
}
return strings;
}
private static List<Token> GetTokens(string text)
{
var tokens = new List<Token>();
foreach (var _char in text)
switch (_char)
{
case ' ':
tokens.Add(Token.Space);
break;
case '\r':
case '\n':
tokens.Add(Token.NewLine);
break;
case '{':
tokens.Add(Token.Open);
break;
case '}':
tokens.Add(Token.Close);
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
tokens.Add(Token.Char);
break;
default:
tokens.Add(Token.UnKnowChar);
break;
}
return tokens;
}
}
}
Have a nice day.
Here's pretty much the same answer as h3e, except without adding the extra Tokens class and enum. We can just treat the string as an array of characters, get the indexes of all the opening and closing braces, and then grab the substrings from between them:
private static IEnumerable<string> GetItems(string text)
{
var items = new List<string>();
var openBraceIndexes = text.Select((chr, index) => new { chr = chr, index })
.Where(item => item.chr == '{').ToList();
var closeBraceIndexes = text.Select((chr, index) => new { chr, index })
.Where(item => item.chr == '}').ToList();
if (openBraceIndexes.Count != closeBraceIndexes.Count)
{
throw new FormatException("text contains an unequal number of open and close braces");
}
for (int i = 0; i < openBraceIndexes.Count; i++)
{
var startIndex = openBraceIndexes[i].index + 1;
var length = closeBraceIndexes[i].index - startIndex;
items.Add(text.Substring(startIndex, length).Trim());
}
return items;
}

C# Switch-case string end with

Is there any way to make a case condition in a switch statement where you say if a string end with something?
switch (Pac.Sku)
{
case "A":
pacVM.Sucursal = "Managua";
break;
case "B":
pacVM.Sucursal = "Masaya";
break;
case "C":
pacVM.Sucursal = "Leon";
break;
default:
pacVM.Sucursal = "N/A";
break;
}
Get the last character of the string, and switch over the result:
switch (Pac.Sku.Last())
{
case 'A':
pacVM.Sucursal = "Managua";
break;
case 'B':
pacVM.Sucursal = "Masaya";
break;
case 'C':
pacVM.Sucursal = "Leon";
break;
default:
pacVM.Sucursal = "N/A";
break;
}
If the string could be null or empty use something like this function instead of Last(). This function returns null if the string is null, null if the string is empty, and the last character of the string if it is not null or empty:
char? GetLast(string s)
{
return s?.Length > 0 ? s.Last() : (char?)null;
}
Switch:
switch(GetLast(Pac.Sku))
You can
use pattern matching feature of C# 7.0 to achieve this. Here is a very basic example:
var t = "blah";
switch (t)
{
case var a when t.EndsWith("bl"):
Console.WriteLine("I'm not here");
break;
case var b when t.EndsWith("ah"):
Console.WriteLine("I'm here");
break;
}
You can get creative with a Func<string, string>[] like this:
Func<string, string>[] cases = new Func<string, string>[]
{
x => x.EndsWith("A") ? "Managua" : null,
x => x.EndsWith("B") ? "Masaya" : null,
x => x.EndsWith("C") ? "Leon" : null,
x => "N/A",
};
Func<string, string> #switch = cases.Aggregate((x, y) => z => x(z) ?? y(z));
string result = #switch(Pac.Sku);
I have tested this with sample input that matches each of the cases and it works just fine.
One significant advantage with this approach is that you can build the Func<string, string>[] at run-time. Nice for creating configurable solutions.
You're also not limited to just using EndsWith - any condition can be used that suits the purpose.
I think it's not a way!
You can only use the if-else
if (Pac.Sku.EndsWith("A") )
{
pacVM.Sucursal= "Managua";
}
else if (Pac.Sku.EndsWith("B"))
{
pacVM.Sucursal= "Masaya";
}
else if (Pac.Sku.EndsWith("C"))
{
pacVM.Sucursal= "Leon";
}
else
{
pacVM.Sucursal= "N/A";
}

How can I make loop instead of switch statement?

How can I write this shorter? For each case I have to write this and then It is too long because there are 48 numbers so I need 48 cases. Is there a way to make a loop?
switch (ballBounce.ToString())
{
case "1":
if (ballBounce == n0)
{
textBox1.Text = number.ToString();
}
break;
case "2":
if (ballBounce == n1)
{
textBox1.Text = number.ToString();
}
break;
case "3":
if (ballBounce == n2)
{
textBox1.Text = number.ToString();
}
break; ...
The loop is useless in this case.
You can use dictionary.
private Dictinoary<string, string> cases = new Dictionary<string, string> {
{"1", "one"},
{"2", "two"},
// ...
};
// in some method
string text;
if (cases.TryGetValue(ballBounce.ToString(), out text)){
this.textBox1.Text = text;
}
If you want something smarter than simple value, you can have functions in the dictionary.
private Dictinoary<string, Func<string>> cases = new Dictionary<string, Func<string>> {
{"1", () => "one"},
{"2", () =>
{
if (DateTime.Now.Seconds % 2 == 0) { return "A"; }
else { return "B"; }
}},
// ...
};
// in some method
Func<string> textProvider;
if (cases.TryGetValue(ballBounce.ToString(), out textProvider)){
this.textBox1.Text = textProvider();
}
Based on your ToString()'s, I'm assuming that ballBounce is an int.
if (ballBounce <= 48 && ballBounce > 0)
{
textBox1.Text = ballBounce.ToString();
}
why do you use if with case?
you don't need to check twice.
also if this is the code for every case
textBox1.Text = number.ToString();
then you don't need switch or if
jsut write textBox1.Text = number.ToString(); and you are good to go.
also if you have some cases ony you can do it that way:
switch (ballBounce.ToString())
{
case "1":
case "2":
case"3":
//....
textBox1.Text = number.ToString();
}

C# need to add random response with switch statement

namespace _7._39
{
class Program
{
static void Main(string[] args)
{
string response1;
string response2;
string response3;
string response4;
Random resp = new Random();
bool correct = Question();// Create a value to call the question method
if (correct== true)// when the answer is true it return very good
{
Console.WriteLine("Very Good!");
}
else// when the answer is false it returns to try again
{
Console.WriteLine("No please try again");
}
}
public static bool Question()
{
Random rand = new Random();// we create a random number
int num = rand.Next(1, 9);// first random number between 1 and 9
int num1 = rand.Next(1, 9);// second random number between 1 and 9
int ans = num * num1;// the value of multiplication between 1 and 2
// asking what the two values are multiplied
Console.WriteLine("What is"+ num.ToString()+ "*" +num1.ToString());
// reads the users attempt
int attempt = int.Parse(Console.ReadLine());
if (attempt == ans)// when the attempt is equal to the answer
{
return true;// its returns true bool
}
else// if it is false it says no please try again
{
Console.WriteLine("No please try again");
return Question();// and creates a new question for the user
}
}
}
}
I need my correct== true and false to respond with a random response among 4 possible choices. I need to do this by doing a switch statement to issue each response. Also by using random to select which response comes up.
Very good!
Excellent!
Nice work!
Keep up the good work!
and 4 options for a false response as well
How can i implement this code into my current code?
response = resp.Next(1, 5);
switch (response)
{
case 1:
Console.WriteLine("Very Good!");
break;
case 2:
Console.WriteLine("Excellent!");
break;
case 3:
Console.WriteLine("Nice Work!");
break;
case 4:
Console.WriteLine("Keep up the good work!");
break;
default;
}
Try this:
var rnd = new Random();
Func<bool, string> getRespose = b =>
{
var choices = b
? new [] { "Very good!", "Excellent!", "Nice work!", "Keep up the good work!", }
: new [] { "Bad!", "V Bad!", "VV Bad!", "VVV Bad!", };
return choices[rnd.Next(0, choices.Length)];
};
No need for a switch statement.
Or if you want it as a switch:
var rnd = new Random();
var choices = (string[])null;
switch (correct)
{
case true:
choices = new []
{ "Very good!", "Excellent!", "Nice work!", "Keep up the good work!", };
break;
case false:
choices = new [] { "Bad!", "V Bad!", "VV Bad!", "VVV Bad!", };
break;
}
var response = choices[rnd.Next(0, choices.Length)];
Or, with a switch and a Func:
var rnd = new Random();
Func<bool, string> getRespose = b =>
{
var choices = (string[])null;
switch (b)
{
case true:
choices = new []
{ "Very good!", "Excellent!", "Nice work!", "Keep up the good work!", };
break;
case false:
choices = new []
{ "Bad!", "V Bad!", "VV Bad!", "VVV Bad!", };
break;
}
return choices[rnd.Next(0, choices.Length)];
};
var response = getRespose(correct);
Or as a "normal" function:
private Random rnd = new Random();
private string GetRespose(bool b)
{
var choices = (string[])null;
switch (b)
{
case true:
choices = new []
{ "Very good!", "Excellent!", "Nice work!", "Keep up the good work!", };
break;
case false:
choices = new []
{ "Bad!", "V Bad!", "VV Bad!", "VVV Bad!", };
break;
}
return choices[rnd.Next(0, choices.Length)];
}
Or as a "normal" function, but without the switch:
private Random rnd = new Random();
private string GetRespose(bool b)
{
var choices = b
? new [] { "Very good!", "Excellent!", "Nice work!", "Keep up the good work!", }
: new [] { "Bad!", "V Bad!", "VV Bad!", "VVV Bad!", };
return choices[rnd.Next(0, choices.Length)];
}

Categories