Password Checker improvement - c#

1.Problem...Its my password validation.COnsoleApp
But i have bug....if first space is null program working(...but i want return false if first char is white
2.Many Condition using
I wanna few using condition..i wanna practise good way
{
bool symb = false;
bool letdig = false;
char currentchar;
char currentchar2;
if (!(pass.Length >= 8 && pass.Length <= 25))
{
return true;
}
string symbols = "!##$%^&*()_-+=[{]};:<>|./?.";
char[] simbolchar = symbols.ToCharArray();
for (int j = 0; j < pass.Length; j++)
{
currentchar = pass[j];
foreach (var simb in simbolchar)
{
if (simb == currentchar)
{
symb = true;
}
}
if (symb)
{
for (int i = 0; i < pass.Length; i++)
{
currentchar2 = pass[i];
if (char.IsUpper(currentchar2) && (char.IsLetterOrDigit(currentchar2)))
{
letdig = true;
}
}
}
if (letdig)
{
Console.WriteLine("WELCOME");
return true;
}
}
return letdig;
}

Solve the first bug can be by adding a condition to check if the string is null or empty before any check after that
public static bool passwordCheck(string pass)
{
bool symb = false;
bool letdig = false;
char currentchar;
char currentchar2;
//Solve the first bug
if (string.IsNullOrEmpty(pass))
{
return false;
}
else
{
if (!(pass.Length >= 8 && pass.Length <= 25))
{
return true;
}
string symbols = "!##$%^&*()_-+=[{]};:<>|./?.";
char[] simbolchar = symbols.ToCharArray();
for (int j = 0; j < pass.Length; j++)
{
currentchar = pass[j];
foreach (var simb in simbolchar)
{
if (simb == currentchar)
{
symb = true;
}
}
if (symb)
{
for (int i = 0; i < pass.Length; i++)
{
currentchar2 = pass[i];
if (char.IsUpper(currentchar2) && (char.IsLetterOrDigit(currentchar2)))
{
letdig = true;
}
}
}
if (letdig)
{
Console.WriteLine("WELCOME");
return true;
}
}
return letdig;
}
}
As for code optimization, you can reading about clear code for your case

Related

Search a word in the given string in C#?

I have to find subtext in text without using builtin function of string.
public static void Main(string[] args)
{
string subtext = "polly";
string text = "polly put the katle on,polly put the katle on,polly put the katle on,we all have tea";
int i, j, found;
int strLen, wordLen;
strLen = text.Length;
wordLen = subtext.Length;
for (i = 0; i < strLen - wordLen; i++)
{
found = 1;
for (j = 0; j < wordLen; j++)
{
if (text[i + j] != subtext[j])
{
found = 0;
break;
}
}
if (found == 1)
{
Console.WriteLine(" found at index:", subtext, i);
Console.ReadLine();
}
}
}
I am not sure how long you would like to search, your current code seems to find all indexes (or at least that seems to be the intent)
Some things you could change however is instead of always starting the loop, you could validate the if the char at position i matches the first char of the subtext, and if not continue.
When you want to write the data to the console, don't forget to add the spaceholders for your arguments, like:
Console.WriteLine("found {0} at index: {1}", subtext, i);
For the rest, I guess your current implementation is okay, but you could add some validations, like ensuring that both texts are available, and if subtext is longer than the text, simply return -1 directly.
For a simple find of first index, I wrote this one up, it still looks pretty similar to yours
private static int FindIn( string text, string sub ) {
if (string.IsNullOrWhiteSpace( text ) || string.IsNullOrWhiteSpace( sub ) ) {
return string.IsNullOrWhiteSpace( sub ) ? 0 : -1;
}
if (text.Length < sub.Length) {
return -1;
}
for (int i = 0; i < text.Length - sub.Length; i++) {
if (text[i] != sub[0]) {
continue;
}
var matched = true;
for (int j = 1; j < sub.Length && i + j < text.Length; j++) {
if (text[i+j] != sub[j]) {
matched = false;
break;
}
}
if (matched) {
return i;
}
}
return -1;
}
Which you can play around with here
There are a lot of pattern-matching algorithms in this book, i will leave here c# implementation of Knuth-Morris-Pratt algorithm.
static int[] GetPrefix(string s)
{
int[] result = new int[s.Length];
result[0] = 0;
int index = 0;
for (int i = 1; i < s.Length; i++)
{
while (index >= 0 && s[index] != s[i]) { index--; }
index++;
result[i] = index;
}
return result;
}
static int FindSubstring(string pattern, string text)
{
int res = -1;
int[] pf = GetPrefix(pattern);
int index = 0;
for (int i = 0; i < text.Length; i++)
{
while (index > 0 && pattern[index] != text[i]) { index = pf[index - 1]; }
if (pattern[index] == text[i]) index++;
if (index == pattern.Length)
{
return res = i - index + 1;
}
}
return res;
}
If you are looking for all occurance of the subtect in the text you can use the following code:
public static void Main(string[] args)
{
string subtext = "polly";
string text = "polly put the katle on,polly put the katle on,polly put the katle on,we all have tea";
int index = 0;
int startPosition = 0;
bool found = false;
while (index < text.Length - 1)
{
if (subtext[0] == text[index])
{
startPosition = index;
index++;
for (int j = 1; j <= subtext.Length - 1; j++)
{
if (subtext[j] != text[index])
{
found = false;
break;
}
else
{
found = true;
}
index++;
}
}
if (found)
{
Console.WriteLine("{0} found at index: {1}", subtext, startPosition);
found = false;
}
index++;
}
Console.ReadLine();
}
If you are looking only for the first occurance add break in the "if (found)" condition

C# Scoping or similar error? Expected number of coin tosses for a specified sequence to appear

This program calculates the expected number of toin cosses until a given sequence will appear. The formula sums powers of two, where powers are those k for which the first k elements of the sequence match the last k elements, in order.
My question is why, when I test it with two different sequences, it only returns one result twice. I assume that it is doing exactly what it looks like and overwriting test1 with test4 when test4 is instanciated, but this code looks to me to be similar to code from smaller exercises that did not have this overwriting behaviour.
This is my second programming course, and my first in C#, neither has been in my mother tongue, so I might be a bit slow with some of the concepts.
I suspect this has to do with one of the lines with public static... (I am not sure how to refer to them) or maybe a protection level. The expectation for test1 should be 38 (2 + 2^2 + 2^5).
using System;
namespace CSProject
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Expectation tests");
PlayerSequence test1 = new PlayerSequence("bc00100");
PlayerSequence test4 = new PlayerSequence("101101");
Console.WriteLine("Expectation of test1 bc00100");
Console.WriteLine (test1.Expectation ());
Console.WriteLine("Expectation of test4 101101");
Console.WriteLine(test4.Expectation());
}
}
class PlayerSequence
{
//ATTRIBUTES
private static bool[] sequence;
//CONSTRUCTORS
public PlayerSequence()
{
}
public PlayerSequence(string sequence_String)//Seems to work!!
{
char[] sequence_array = sequence_String.ToCharArray();
int inputLength = sequence_array.Length;
int sequence_length = 0;
for( int i = 0; i < inputLength; i++) {
if (sequence_array[i] == '1' || sequence_array[i] == '0') {
sequence_length++;
}
}
sequence = new bool[sequence_length];///KEYItem
int input_index_adjustment = 0;
for (int i = 0; i < inputLength; i++) {
int sVal;
if (!Int32.TryParse(sequence_String[i].ToString(), out sVal))
{
input_index_adjustment++;
continue;
}
if (sVal == (Int32)1)
PlayerSequence.sequence[i - input_index_adjustment] = true;
if (sVal == (Int32)0)
PlayerSequence.sequence[i - input_index_adjustment] = false;
if(sVal != 1 && sVal != 0)
input_index_adjustment++;
}
}
public override string ToString()//Works
{
string retString;
retString = "";
for (int i = 0; i < sequence.Length;i++) {
if (sequence[i] == true) retString = retString + "T ";
else retString = retString + "H ";
}
return retString;
}
public ulong Expectation(){
ulong espTA = 0;
for (int kexp = 0; kexp < /*PlayerSequence.*/sequence.Length; kesp++)
{
if(SeqCheck(sequence,kesp+1))
expTA = expTA + (ulong)Math.Pow(2, kexp+1);
}
return espTA;
}//end Expectation
public static bool SeqCheck(bool[] toCheck, int k){
//Test of required property for each power of 2 here k
int a = toCheck.Length ;
bool seqgood = false;
bool[] checkStart = new bool[k];
bool[] checkEnd = new bool[k];
for (int i = 0; i < k; i++) {//loop sets up subarrays to compare
checkStart[i] = toCheck[i];
checkEnd[i] = toCheck[a - k + i];
}
for (int i = 0; i < k; i++){//loop does comparison
if(checkStart[i] != checkEnd[i])
{
seqgood = false;
break;
}
seqgood = true;
}
return seqgood;
}//end SeqCheck
}//end PlayerSequence class
}//End this section of the namespace
It is your use of the static keyword for the local variable in your class. By doin so, you make the variable a part of the type (PlayerSequence) and not the instance of PlayerSequence (test1, test4). Below worked on my machine.
class PlayerSequence
{
//ATTRIBUTES
private bool[] sequence;
//CONSTRUCTORS
public PlayerSequence()
{
}
public PlayerSequence(string sequence_String)//Seems to work!!
{
char[] sequence_array = sequence_String.ToCharArray();
int inputLength = sequence_array.Length;
int sequence_length = 0;
for (int i = 0; i < inputLength; i++)
{
if (sequence_array[i] == '1' || sequence_array[i] == '0')
{
sequence_length++;
}
}
sequence = new bool[sequence_length];///KEYItem
int input_index_adjustment = 0;
for (int i = 0; i < inputLength; i++)
{
int sVal;
if (!Int32.TryParse(sequence_String[i].ToString(), out sVal))
{
input_index_adjustment++;
continue;
}
if (sVal == (Int32)1)
sequence[i - input_index_adjustment] = true;
if (sVal == (Int32)0)
sequence[i - input_index_adjustment] = false;
if (sVal != 1 && sVal != 0)
input_index_adjustment++;
}
}
public override string ToString()//Works
{
string retString;
retString = "";
for (int i = 0; i < sequence.Length; i++)
{
if (sequence[i] == true) retString = retString + "T ";
else retString = retString + "H ";
}
return retString;
}
public ulong Expectation()
{
ulong espTA = 0;
for (int kexp = 0; kexp < sequence.Length; kexp++)
{
if (SeqCheck(sequence, kexp + 1))
espTA = espTA + (ulong)Math.Pow(2, kexp + 1);
}
return espTA;
}//end Expectation
public bool SeqCheck(bool[] toCheck, int k)
{
//Test of required property for each power of 2 here k
int a = toCheck.Length;
bool seqgood = false;
bool[] checkStart = new bool[k];
bool[] checkEnd = new bool[k];
for (int i = 0; i < k; i++)
{//loop sets up subarrays to compare
checkStart[i] = toCheck[i];
checkEnd[i] = toCheck[a - k + i];
}
for (int i = 0; i < k; i++)
{//loop does comparison
if (checkStart[i] != checkEnd[i])
{
seqgood = false;
break;
}
seqgood = true;
}
return seqgood;
}//end SeqCheck
}

Performance issue with traversing&&filtering datagridview in c#

Currently, I am doing a log analyzer for my personal project.
My issue here is that I am new to c# and I have an performance issue with my tool.
Everytime the device(iOS) is interacted, I get an output syslog from a library and it comes in to the output handler.
public void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine, iosSyslogger form, string uuid)
{
string currentPath = System.Environment.CurrentDirectory;
bool exit = false;
if (exit == true) return;
try
{
form.BeginInvoke(new Action(() =>
{
form.insertLogText = outLine.Data;
}));
using (System.IO.StreamWriter file = new System.IO.StreamWriter(currentPath + #"\syslog" + uuid + ".txt", true))
{
file.WriteLine(outLine.Data);
}
}
catch
{
return ;
}
//*Most of the logic for outputing the log should be dealt from this output Handler
}
Then, I write the outline.Data to Data grid view. My concern is that I need to be able to search and filter through data gridview.
Curently I am using visibility = false for search filtering ( if the row does not match the given filter specification I set the row to visibility =false)
This requires the program to traverse the entire datagridview to check whether the condition is met.
Will there be any better way to filter and search within ?
(When I have thousands of lines of row, it takes at least 20 seconds to process it)
Below is the code for filtering, and searching through the results function.
private void searchResult(string term)
{
if (term != null)
{
int i = 0;
while (i < dataGridView1.Rows.Count - 1)
{
if (dataGridView1.Rows[i].Cells[3] == null)
{
i++;
continue;
}
if (dataGridView1.Rows[i].Visible == false)
{
i++;
continue;
}
else if (dataGridView1.Rows[i].Cells[2].Value.ToString().Contains(term) || dataGridView1.Rows[i].Cells[3].Value.ToString().Contains(term) || dataGridView1.Rows[i].Cells[4].Value.ToString().Contains(term))
{
string multirow = dataGridView1.Rows[i].Cells[5].Value.ToString();
int count = Convert.ToInt32(multirow);
if (count > 0)
{
int z = 0;
for (z = 0; z <= count; z++)
{
dataGridView1.Rows[i + z].Visible = true;
}
i = i + z;
}
else
{
dataGridView1.Rows[i].Visible = true;
i++;
}
}
else
{
dataGridView1.Rows[i].Visible = false;
i++;
}
}
}
}
public filteringThelist(){
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
dataGridView1.Rows[i].Visible = false;
int count1,count2,count3=0;
count1 = 1;
count2 = 1;
count3 = 1;
int z = 0;
foreach (KeyValuePair<string, string> entry in totalSelected)
{
if (entry.Value == "devicename" && dataGridView1.Rows[i].Cells[1].Value != null)
{
if (dataGridView1.Rows[i].Cells[1].Value.ToString().Trim().Equals(entry.Key.Trim()))
{
string multirow1 = dataGridView1.Rows[i].Cells[5].Value.ToString();
int counts = Convert.ToInt32(multirow1);
if (counts > 0)
{
for (z = 0; z < counts; z++)
{
dataGridView1.Rows[i + z].Visible = true;
}
}
else
{
dataGridView1.Rows[i].Visible = true;
}
}
else if (devicename.CheckedItems.Count > 1&&count1!= devicename.CheckedItems.Count)
{
count1++;
continue;
}
else
{
dataGridView1.Rows[i].Visible = false;
break;
}
}
else if (entry.Value == "process" && dataGridView1.Rows[i].Cells[2].Value != null)
{
if (dataGridView1.Rows[i].Cells[2].Value.ToString().Trim().Equals(entry.Key.Trim()))
{
string multirow1 = dataGridView1.Rows[i].Cells[5].Value.ToString();
int counts = Convert.ToInt32(multirow1);
if (counts > 0)
{
for (z = 0; z < counts; z++)
{
dataGridView1.Rows[i + z].Visible = true;
}
}
else
{
dataGridView1.Rows[i].Visible = true;
}
}
else if (processlistname.CheckedItems.Count > 1 && count2 != processlistname.CheckedItems.Count)
{
count2++;
continue;
}
else
{
dataGridView1.Rows[i].Visible = false;
break;
}
}
else if (entry.Value == "loglevel" && dataGridView1.Rows[i].Cells[3].Value != null)
{
if (dataGridView1.Rows[i].Cells[3].Value.ToString().Trim().Contains(entry.Key.Trim()))
{
string multirow1 = dataGridView1.Rows[i].Cells[5].Value.ToString();
int counts = Convert.ToInt32(multirow1);
if (counts > 0)
{
for (z = 0; z < counts; z++)
{
dataGridView1.Rows[i + z].Visible = true;
}
}
else
{
dataGridView1.Rows[i].Visible = true;
}
continue;
}
else if (loglevelCheckBox.CheckedItems.Count > 1 && count3 != loglevelCheckBox.CheckedItems.Count)
{
count3++;
continue;
}
else
{
dataGridView1.Rows[i].Visible = false;
break;
}
}
// do something with entry.Value or entry.Key
}
string multirow = dataGridView1.Rows[i].Cells[5].Value.ToString();
int count = Convert.ToInt32(multirow);
if (count > 0&& dataGridView1.Rows[i].Visible==false)
{
for (int k = 0; k <= count; k++)
{
dataGridView1.Rows[i + k].Visible = false;
}
}
i = i + z;
}
The performance problem is because your DataGridView is redrawing at each modification.
Don't fill the DataGridView directly from your Data. Rather create a DataTable and bind it to DataGridView with a BindingSource.
Then use the "Filter" property of the binding source to view extracts of dataTable in the DataGridView. The "Filter" property is a string whose content is similar to that of a WHERE SQL clause.

StackOverflow exception in a recursive method

I've written a recursive method in C# that should indent strings. For example, this string:
for (int i = 0; i < sb.Length; i++)
{
if (sb[i] == '{')
{
startIndex = i;
break;
}
}
should be converted to:
for (int i = 0; i < sb.Length; i++)
{
if (sb[i] == '{')
{
startIndex = i;
break;
}
}
My method is (updated):
private static string IndentText(string t,bool first = true)
{
if (first == false)
{
t = t.PadLeft(2);
}
int startIndex = t.IndexOf('{') + 1;
int stopIndex = t.LastIndexOf('}') - 1;
int blockLength = stopIndex - startIndex + 1;
if (blockLength <= 1 )
{
return "";
}
string start = t.Substring(0, startIndex);
string end = t.Substring(stopIndex + 1);
string indentBlock = t.Substring(startIndex, blockLength);
if (!CheckNestedBlocks(indentBlock))
{
return indentBlock;
}
return start + IndentText(indentBlock,false) + end;
}
private static bool CheckNestedBlocks(string t)
{
for (int i = 0; i < t.Length; i++)
{
if (t[i] == '{') // { and } always come in pairs, so I can check of only one of then
{
return true;
}
}
return false;
}
But I'm getting a StackOverflow exception in mscorlib.dll
What is my mistake? Thanks in advance.
By the way, because I think I'm complicating this problem, is there a better (and working) way to indent strings like this?
You should not include the braces in the "block" that is passed in the recursive call:
if (t[i] == '{')
{
startIndex = i + 1; // Start one character beyond {
break;
}
// ...
if (t[i] == '}')
{
stopIndex = i - 1; // Stop one character prior to }
break;
}

how to use string.compare

There is an error with that string.compiler thingy and i dont know what to do. i really need some help please
char[] valWord = new char[100];
Console.WriteLine(textBox1.Text);
valWord = textBox1.Text;
int beg = 0;
int val = 0;
int value = 0;
for (int i = 0; i < 100; i++)
{
if (valWord[i] == ' ' || valWord[i] == '\0')
{
char[] temp = new char[100];
for (int j = 0; j < i - beg; j++)
{
temp[j] = valWord[beg + j];
}
temp[i - beg] = '\0';
//there is an error in this if statement: String.Compare
if (String.Compare(temp, "thousand") == 0)
{
value += (val*1000);
val = 0;
}
else if (String.Compare(temp, "hundred") == 0)
{
value += (val*100);
val = 0;
}
else if (String.Compare(temp, "one") == 0)
{
val = 1;
}
else if (String.Compare(temp, "two") == 0)
{
val = 2;
}
if (valWord[i] == '\0')
{
value += val;
break;
}
}
Console.WriteLine(textBox2.Text);
}
else
{
_list.Add(name, new GenericList());
}
You can't compare a string to a char array. They are different types.
Use if (string.Equals(new string(temp),"thousand")) instead.
As per MSDN, there is no such function overload defined for String.Compare

Categories

Resources