How do I use string.replace() with chars? - c#

So full disclousre this is homework. Anyway trying to make a morse code converter and I am just stuck on this last issue. I want to use chars and then use string.replace but I can't since my dictionary is all strings. I want to use chars though. So how would I get around this?
public void InputReader()
{
string inputForTranslating = inputForTranslator.Text;
Dictionary<string, string> morseDictionary = new Dictionary<string, string>
{
{ " ", " " }, { ",", "--..--" }, { ".", ".-.-.-" }, { "\\?", "..--.." }, { "0", "-----" }, { "1", ".----" }, { "2", "..---" }, { "3", "...--" },
{ "4", "....-" }, { "5", "....." }, { "6", "-...." }, { "7", "--..." }, { "8", "---.." }, { "9", "----." }, { "A", ".-" },
{ "B", "-..." }, { "C", "-.-." }, { "D", "-.." }, { "E", "." }, { "F", "..-." }, { "G", "--." }, { "H", "...." }, { "I", ".." },
{ "J", ".---" }, { "K", "-.-" }, { "L", ".-.." }, { "M", "---" }, { "N", "-." }, { "O", "---" }, { "P", ".--." }, { "Q", "--.-" },
{ "R", ".-." }, { "S", "..." }, { "T", "-" }, { "U", "..-" }, { "V", "...-" }, { "W", ".--" }, { "X", "-..-" }, { "Y", "-.--" },
{ "Z", "--.." }
};
char[] charArray = inputForTranslating.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
outPutTranslation.Text = outPutTranslation.ToString().Replace(morseDictionary.Keys, morseDictionary.Values); ////This is where the error occurs "cannot convert from 'System.Collections.Generic.Dictionary<string, string>.KeyCollection' to 'char'"
}
}

Replace takes strings/chars as parameters, not a collection of keys or values.
In this case, you don't even need the Replace, you can just add the values based on the keys.
Also, your outPutTranslation.Text will only have the last char.
Dictionary<string, string> morseDictionary = new Dictionary<string, string>
{
{ " ", " " }, { ",", "--..--" }, { ".", ".-.-.-" }, { "\\?", "..--.." }, { "0", "-----" }, { "1", ".----" }, { "2", "..---" }, { "3", "...--" },
{ "4", "....-" }, { "5", "....." }, { "6", "-...." }, { "7", "--..." }, { "8", "---.." }, { "9", "----." }, { "A", ".-" },
{ "B", "-..." }, { "C", "-.-." }, { "D", "-.." }, { "E", "." }, { "F", "..-." }, { "G", "--." }, { "H", "...." }, { "I", ".." },
{ "J", ".---" }, { "K", "-.-" }, { "L", ".-.." }, { "M", "---" }, { "N", "-." }, { "O", "---" }, { "P", ".--." }, { "Q", "--.-" },
{ "R", ".-." }, { "S", "..." }, { "T", "-" }, { "U", "..-" }, { "V", "...-" }, { "W", ".--" }, { "X", "-..-" }, { "Y", "-.--" },
{ "Z", "--.." }
};
string output = "";
foreach (char c in inputForTranslating.ToCharArray())
{
output += morseDictionary[c];
}
outPutTranslation.Text = output;

Well, string.Replace() works both with two chars or two strings. The error clearly states that morseDictionary.Keys is not a string. Neither is morseDictionary.Values. And it's right, they are the list of keys and values of the dictionary!
There's another mistake in that code. You're converting your input to a char array, and then iterating each character, and trying to replace there. Think about what it's doing:
If you have -.-, in the first iteration you will search over -, in the second over . and lastly over -. You'll never be able to find the K.
You should iterate your dictionary, and search each word in the whole string.
foreach(string key in morseDictionary) {
//for morse->letter
inputForTranslating=inputForTranslating.Replace(morseDictionary[key],key);
//for letter->morse
inputForTranslating=inputForTranslating.Replace(key,morseDictionary[key]);

Related

After comparing the array data of the request data and the array data of the response data through the lambda expression, add the list

I am making an api server
The client sends the request data like this
{
"classCode": "01",
"array": [
{
"GroupID": "Class",
"CodeID": "A",
"Value": "1"
},
{
"GroupID": "Class",
"CodeID": "B",
"Value": "1"
},
{
"GroupID": "Class",
"CodeID": "C",
"Value": "1"
},
{
"ClassID": "Class",
"CodeID": "D",
"Value": "1"
}
]
}
The api server being created receives the requested data in this way and sends the response data.
public List<user_model> List(Dictionary<string, object> param)
{
.. code omission
List<user_model> tempList = new List<user_model>();
List<user_model> resultList = new List<user_model>();
jsonReq.Session = param;
.. code omission
}
First, the received data is stored in the templist
{
"Code": "00",
"Msg": "SUCCESS",
"Data": [
{
"className": "aClass",
"array": [
{
"GroupID": "Class",
"CodeID": "A",
"Value": "1"
},
{
"GroupID": "Class",
"CodeID": "B",
"Value": "1"
},
{
"GroupID": "Class",
"CodeID": "C",
"Value": "1"
},
{
"GroupID": "Class",
"CodeID": "D",
"Value": "1"
},
{
"GroupID": "Class",
"CodeID": "E",
"Value": "1"
}
]
},
{
"className": "bClass",
"array": [
{
"GroupID": "Class",
"CodeID": "A",
"Value": "1"
},
{
"GroupID": "Class",
"CodeID": "B",
"Value": "1"
},
{
"GroupID": "Class",
"CodeID": "C",
"Value": "1"
},
{
"GroupID": "Class",
"CodeID": "D",
"Value": "0"
},
{
"GroupID": "Class",
"CodeID": "E",
"Value": "1"
}
]
},
{
"className": "cClass",
"array": [
{
"GroupID": "Class",
"CodeID": "A",
"Value": "1"
},
{
"GroupID": "Class",
"CodeID": "B",
"Value": "1"
},
{
"GroupID": "Class",
"CodeID": "C",
"Value": "1"
},
{
"GroupID": "Class",
"CodeID": "D",
"Value": "0"
},
{
"GroupID": "Class",
"CodeID": "E",
"Value": "0"
}
]
}
]
}
I am going to filter and put only the data containing "aClass" back in the resultList
I want to express it in a lambda expression, but I get an error in the code I wrote.
resultList .AddRange(tempList .Where(um =>
um.array[0].Value.Equals(param["array"].ToString()) &&
um.array[1].Value.Equals(param["array"].ToString()) &&
um.array[2].Value.Equals(param["array"].ToString()) &&
um.array[3].Value.Equals(param["array"].ToString())));
How can I modify the lambda expression to insert the desired value?
Without knowing how you generated tempList from the recievedData its going to be hard to debug - but two places to look for would be:
Comparing a single value in the array with the entire param["array"] object
Indexing 4 times into the tempList array which might only have 3 values
I assume its the former - perhaps you wanted something like:
var arrayArray = ((IEnumerable)param["array"]).ToArray();
resultList.AddRange(tempList.Where(um =>
um.array[0].Value.Equals(arrayArray[0].ToString()) &&
um.array[1].Value.Equals(arrayArray[1].ToString()) &&
um.array[2].Value.Equals(arrayArray[2].ToString()) &&
um.array[3].Value.Equals(arrayArray[3].ToString())));

selecting value not index from drop down c#

Forgive, new to c# always been a PHP man.
Have a form to generator random string for passwords based on the number of characters selected from drop down.
Having a problem with obtaining the values from drop down (casting the object to an int).
code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string endword = "";
int chrnumber = Convert.ToInt16(comboBox1.SelectedValue);
string[] Nochars = { "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "#", "z", "x", "c", "v", "b", "n", "m", "/", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "{", "}", "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "#", "~", "Z", "X", "C", "V", "B", "N", "M", "<", ">", "?", "!", "£", "$", "%", "^", "&", ".*", "(", ")", "_", "+", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=" };
Random rndchar = new Random();
for (int i = 0; i < chrnumber; i++)
{
int iSelect = rndchar.Next(0, Nochars.Length);
string word1 = Nochars[iSelect];
string word2 = word1;
if (i == 0) { endword = word1; } else { endword += "." + word2; }
}
pwd.Text = endword;
}
//On form load
public Form1(){
List<Values> reasons = new List<Values> {
new Values("0", 0),
new Values("1", 1),
new Values("2", 2),
new Values("3", 3),
new Values("4", 4),
new Values("5", 5) };
comboBox1.DataSource = reasons;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
reason = Convert.ToInt32(comboBox1.SelectedValue);
}
here the default value is 0, so your error will not occur at any point. I hope your combox datasource default value has ", which is causing this error.
or make sure the value part is not a alphabets/other characters instead of numbers in your datasource.
try this
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string endword = "";
int chrnumber = int.Parse(this.comboBox1.GetItemText(this.comboBox1.SelectedItem).ToString());// change line
string[] Nochars = { "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "#", "z", "x", "c", "v", "b", "n", "m", "/", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "{", "}", "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "#", "~", "Z", "X", "C", "V", "B", "N", "M", "<", ">", "?", "!", "£", "$", "%", "^", "&", ".*", "(", ")", "_", "+", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=" };
Random rndchar = new Random();
for (int i = 0; i < chrnumber; i++)
{
int iSelect = rndchar.Next(0, Nochars.Length);
string word1 = Nochars[iSelect];
string word2 = word1;
if (i == 0) {
endword = word1;
}
else {
endword += "." + word2;
}
}
pwd.Text = endword;
}

How to calculate the sum of column score and time

I have a 2-dimensional array like below.
If I want to sum all time and score of rows of Each ID that start from lesson startpoint=E and ends by lesson endspoint=I. In the case below, for ID 1 it become (time=190+195+200=585 and score=3+3+4=10) and ID 3 that (time=190+210+160=560 and score=5+4+4=13).
I already came up with following loop.
ID Lesson Time Score
1 C 165 4
1 E 190 3
1 H 195 3
1 I 200 4
2 A 100 2
2 B 150 5
2 D 210 2
2 E 110 4
3 D 130 5
3 E 190 5
3 H 210 4
3 I 160 4
3 J 110 4
4 E 120 3
4 H 150 4
4 J 170 4
-
for (int i=0; i<SizeofDataGrid;i++)//save datatable into array
{
for (int j=0; j<4;j++)
{
FILTERED[i,j]=Convert.ToString(interaction.Rows[i][j]);
}
}
for (int i = 0; i < FILTERED.GetLength(0); i++)
{
string UNIQUEID = UniqueUserId[i];
for (int j = 0; j < SizeofDataGrid; j++)
{
if (UNIQUEID == FILTERED[j,0])// match ID
{
for (int x = 0; x < SizeofDataGrid; x++)
{
if (startpoint == FILTERED[j, 1]) //Match start Lesson
{
TotalTime[1, i] = TotalTime[1, i] + Convert.ToUInt16(FILTERED[j, 2]);
TotalTime[0, i] = i;
TotalScore[1, i] = TotalScore[1, i] + Convert.ToUInt16(FILTERED[j, 3]);
TotalScore[0, i] = i;
}
}
}
}
}
Try this:
// this method does the calculations then puts the values in the totalScore and totaltime variables
public void DoCalculations(string[,] data, string id, out int totalScore, out int totalTime)
{
totalTime = 0;
totalScore = 0;
for (int i = 0; i < data.GetLength(0); i++)
{
if (data[i, 0] != id) continue;
// modify this string to contain the lessons between E and I
if (!"EFGHI".Contains(data[i, 1])) continue;
// do proper error checking unless you're sure they'll always be integers
totalTime += int.Parse(data[i, 2]);
totalScore += int.Parse(data[i, 3]);
}
}
And this is the usage example:
string[,] data = new string[,]
{
{"1", "C", "165", "4"},
{"1", "E", "190", "3"},
{"1", "H", "195", "3"},
{"1", "I", "200", "4"},
{"2", "A", "100", "2"},
{"2", "B", "150", "5"},
{"2", "D", "210", "2"},
{"2", "E", "110", "4"},
{"3", "D", "130", "5"},
{"3", "E", "190", "5"},
{"3", "H", "210", "4"},
{"3", "I", "160", "4"},
{"3", "J", "110", "4"},
{"4", "E", "120", "3"},
{"4", "H", "150", "4"},
{"4", "J", "170", "4"}
};
// will store the total score
int totalScore = 0;
// will store the total time
int totalTime = 0;
// calling the function for the id=3
DoCalculations(data, "3", out totalScore, out totalTime);
Console.WriteLine(totalTime); // will output: 560
Console.WriteLine(totalScore); // will output: 13
Do you know about the break statement? You should be able to create a conditional statement that checks for your condition, then put break; at the bottom of it and you will exit the loop.
I would try to avoid using string[,] FILTERED to store your data. You really can easily create strong data types instead. However, if you must use it then I would convert to a strong data type and then do the calculations.
So, starting with the raw data:
string[,] FILTERED = new string[16, 4]
{
{ "1", "C", "165", "4" },
{ "1", "E", "190", "3" },
{ "1", "H", "195", "3" },
{ "1", "I", "200", "4" },
{ "2", "A", "100", "2" },
{ "2", "B", "150", "5" },
{ "2", "D", "210", "2" },
{ "2", "E", "110", "4" },
{ "3", "D", "130", "5" },
{ "3", "E", "190", "5" },
{ "3", "H", "210", "4" },
{ "3", "I", "160", "4" },
{ "3", "J", "110", "4" },
{ "4", "E", "120", "3" },
{ "4", "H", "150", "4" },
{ "4", "J", "170", "4" },
};
I would first turn this into strongly-type data:
var data =
FILTERED
.Cast<string>()
.Select((x, n) => new { x, n })
.GroupBy(xn => xn.n / 4, xn => xn.x)
.Select(xs => new
{
ID = int.Parse(xs.ElementAt(0)),
Lession = xs.ElementAt(1),
Time = int.Parse(xs.ElementAt(2)),
Score = int.Parse(xs.ElementAt(3)),
});
This gives:
I would then do this query:
var result =
data
.GroupBy(x => x.ID)
.Select(xs => new
{
ID = xs.Key,
Lessions = xs
.Where(x => x.Lession.Intersect("EFGHI").Any())
.ToArray(),
})
.Select(x => new
{
x.ID,
Time = x.Lessions.Sum(y => y.Time),
Score = x.Lessions.Sum(y => y.Score),
})
.ToArray();
That gives me this result:
Now, just as an alternative to mucking around with the intermediate FILTERED array you could just get the data directly from the DataTable like this:
var data =
from row in interaction.Rows.Cast<DataRow>()
select new
{
ID = row.Field<int>(0),
Lession = row.Field<string>(1),
Time = row.Field<int>(2),
Score = row.Field<int>(3),
};

Decoding Morse Code to Text

When I try to replace the the inputed morse code into text I get a problem. Basically the problem is that when the user inputs the ".", the prorgram prints the letter "E"(which is "." in morse code) and ignores all of the other periods after it to make other letters with two or more consecutive periods.
How should I solve this?
I know that this is probably a very newbie question but I've been struggling all day to find an answer for this.
Here's the code
public partial class Morsetext : PhoneApplicationPage
{
public string[] aakkoset = { ".", "A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T",
"U", "V","W", "X", "Y",
"Z", "Ä", "Ö", "0", "1",
"2", "3", "4", "5", "6",
"7", "8", "9", "?", ":",
",", "#", "/", "=", " ",
};
public string[] morse = {".-.-.-", ".-", "-...", "-.-.", "-..", ".",
"..-.", "--.", ".... ", "..", ".---",
"-.-", ".-..", "--", "-.", "---",
".--.", "--.-", ".-.", "...", "-",
"..-", "...-", ".--", "-..-", "-.--",
"--..", ".-.-", "---.", "-----", ".----",
"..---", "...--", "....-", ".....", "-....",
"--...", "---..","----.", "..--..", "---...",
"-....-", ".--.-.", "-..-.", "-...-", " ",
};
public Morsetext()
{
InitializeComponent();
}
private void bShort_Click(object sender, RoutedEventArgs e)
{
char piste = '.';
tBoxMorse2.Text += piste.ToString();
}
private void tBoxMorse2_TextChanged(object sender, TextChangedEventArgs e)
{
tBlockText2.Text = tBoxMorse2.Text.ToUpper()
.Replace(morse[0],aakkoset[0])
.Replace(morse[1],aakkoset[1])
.Replace(morse[2],aakkoset[2])
.Replace(morse[3],aakkoset[3])
.Replace(morse[4],aakkoset[4])
.Replace(morse[5],aakkoset[5])
.Replace(morse[6],aakkoset[6])
.Replace(morse[7],aakkoset[7])
.Replace(morse[8],aakkoset[8])
.Replace(morse[9],aakkoset[9])
.Replace(morse[10],aakkoset[10])
.Replace(morse[11],aakkoset[11])
.Replace(morse[12],aakkoset[12])
.Replace(morse[13],aakkoset[13])
.Replace(morse[14],aakkoset[14])
.Replace(morse[15],aakkoset[15])
.Replace(morse[16],aakkoset[16])
.Replace(morse[17],aakkoset[17])
.Replace(morse[18],aakkoset[18])
.Replace(morse[19],aakkoset[19])
.Replace(morse[20],aakkoset[20])
.Replace(morse[21],aakkoset[21])
.Replace(morse[22],aakkoset[22])
.Replace(morse[23],aakkoset[23])
.Replace(morse[24],aakkoset[24])
.Replace(morse[25],aakkoset[25])
.Replace(morse[26],aakkoset[26])
.Replace(morse[27],aakkoset[27])
.Replace(morse[28],aakkoset[28])
.Replace(morse[29],aakkoset[29])
.Replace(morse[30],aakkoset[30])
.Replace(morse[31],aakkoset[31])
.Replace(morse[32],aakkoset[32])
.Replace(morse[33],aakkoset[33])
.Replace(morse[34],aakkoset[34])
.Replace(morse[35],aakkoset[35])
.Replace(morse[36],aakkoset[36])
.Replace(morse[37],aakkoset[37])
.Replace(morse[38],aakkoset[38])
.Replace(morse[39],aakkoset[39])
.Replace(morse[40],aakkoset[40])
.Replace(morse[41],aakkoset[41])
.Replace(morse[42],aakkoset[42])
.Replace(morse[43],aakkoset[43])
.Replace(morse[44],aakkoset[44]);
}
Morse code can be decoded using dichotomic search. The decision tree looks something like this
The simplest solution is to reorder your replaces from longest morse string first to shortest morse string last.

how do I replace numbers using regex?

I am using C# regex library to do some text find and replace.
I would like to change the following:
1 -> one
11 -> one one
123 -> one two three
for example, here's my code to replace ampersand:
string pattern = "[&]";
string replacement = " and ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(text, replacement);
Edit
I found some great examples of .NET RegEx on MSDN:
http://msdn.microsoft.com/en-us/library/kweb790z.aspx
Since you're specifically asking for a regex, you could do something like this
var digits = new Dictionary<string, string> {
{ "0", "zero" },
{ "1", "one" },
{ "2", "two" },
{ "3", "three" },
{ "4", "four" },
{ "5", "five" },
{ "6", "six" },
{ "7", "seven" },
{ "8", "eight" },
{ "9", "nine" }
};
var text = "this is a text with some numbers like 123 and 456";
text = Regex.Replace(text, #"\d", x => digits[x.Value]);
which will give you
this is a text with some numbers like onetwothree and fourfivesix

Categories

Resources