This question already has answers here:
Iterating through the Alphabet - C# a-caz
(10 answers)
Closed 8 years ago.
I am trying to increment an alphanumeric string using a given charset
say the input is 0000a
then the output should be 0000b
However when the input reaches the defined limit, say zzzzz
it should reset to 00001
I have read the following Increment of Alphabet in c#
using
char c
c++
seem to be the best way to do this.
I have the following class
Namespace BatchNo_Generator
{
class RandomStringGenerator
{
public enum Mode
{
ALPHANUMERIC = 1,
ALPHA = 2,
NUMERIC = 3,
}
public string genbase(int length, string mode)
{
int j = 0;
if (mode == "ALPHANUMERIC")
{
StringBuilder s = new StringBuilder();
while (j < length - 1)
{
s.Insert(0, "0");
j++;
}
s.Insert(s.Length, "1");
return s.ToString();
}
if (mode == "ALPHA")
{
StringBuilder s = new StringBuilder();
while (j < length - 1)
{
s.Insert(0, "a");
j++;
}
s.Insert(s.Length, "a");
return s.ToString();
}
if (mode == "NUMERIC")
{
StringBuilder s = new StringBuilder();
while (j < length - 1)
{
s.Insert(0, "0");
j++;
}
s.Insert(s.Length, "1");
return s.ToString();
}
return "";
}
public string gennext(string current, string mode, char endchar)
{
StringBuilder s = new StringBuilder(current);
int i = current.Length;
if (mode == "ALPHA")
{
for (int j = i; j > 0; j--)
{
if (checkend(s[j - 1], endchar, 'a', mode) == true)
{
s[j] = resetchar(s[j], 'a');
incrementchar(s[j + 1], mode);
}
else
{
char c = incrementchar(s[j - 1], mode);
s.Remove(j - 1, 1);
s.Insert(j - 1, c);
break;
}
}
return s.ToString();
}
if (mode == "NUMERIC")
{
for (int j = i; j > 0; j--)
{
if (checkend(s[j - 1], endchar, '0', mode) == true)
{
s[j-1] = resetchar(s[j-1], '0');
incrementchar(s[j - 1], mode);
}
else
{
char c = incrementchar(s[j - 1], mode);
s.Remove(j - 1, 1);
s.Insert(j - 1, c);
}
}
return s.ToString();
}
if (mode == "ALPHANUMERIC")
{
for (int j = i; j > 0; j--)
{
if (checkend(s[j - 1], endchar, '0', mode) == true)
{
s[j-1] = resetchar(s[j-1], '0');
char c = incrementchar(s[j - 1], mode);
}
else
{
{
char c = incrementchar(s[j - 1], mode);
s.Remove(j - 1, 1);
s.Insert(j - 1, c);
break;
}
}
}
return s.ToString();
}
return "";
}
public char incrementchar(char c, string mode)
{
char cnew = c++;
switch (mode)
{
case "ALPHA":
{
if (char.IsLetter(c) == false) { cnew++; }
else { return char.ToLower(c); }
break;
}
case "NUMERIC":
{
if (char.IsDigit(c) == false) { cnew++; }
else { return c; }
break;
}
case "ALPHANUMERIC":
{
while (char.IsLetterOrDigit(c) == false) { c++; }
// if (char.IsLetterOrDigit(c) == false) { cnew++; }
// else { return char.ToLower(c); }
return char.ToLower(c);
break;
}
}
return '?';
}
public bool checkend(char current, char end, char start, string mode)
{
if (current == end) { return true; }
else { return false; }
}
public char resetchar(char inputchar, char defaultchar)
{
return defaultchar;
}
public static IEnumerable<string> GetColumns(char startchar, char endchar)
{
string s = null;
for (char c2 = startchar; c2 <= endchar + 1; c2++)
{
for (char c = 'A'; c <= 'Z'; c++)
{
if (char.IsLetter(c) == true)
{
yield return s + char.ToLower(c);
}
}
if (char.IsLetterOrDigit(c2) == true)
{
s = c2.ToString();
}
}
}
}
}
Which I tried with
RandomStringGenerator test = new RandomStringGenerator();
MessageBox.Show(test.gennext("0zzzz","ALPHANUMERIC",'0'));
The issue I have is that this input 0zzzz returns 0zzzÂȘ
Any help would be appreciated
The code is sloppy I know, i will be cleaning it up when I get a working set
public enum Mode
{
AlphaNumeric = 1,
Alpha = 2,
Numeric = 3
}
public static string Increment(string text, Mode mode)
{
var textArr = text.ToCharArray();
// Add legal characters
var characters = new List<char>();
if (mode == Mode.AlphaNumeric || mode == Mode.Numeric)
for (char c = '0'; c <= '9'; c++)
characters.Add(c);
if (mode == Mode.AlphaNumeric || mode == Mode.Alpha)
for (char c = 'a'; c <= 'z'; c++)
characters.Add(c);
// Loop from end to beginning
for (int i = textArr.Length - 1; i >= 0; i--)
{
if (textArr[i] == characters.Last())
{
textArr[i] = characters.First();
}
else
{
textArr[i] = characters[characters.IndexOf(textArr[i]) + 1];
break;
}
}
return new string(textArr);
}
// Testing
var test1 = Increment("0001", Mode.AlphaNumeric);
var test2 = Increment("aab2z", Mode.AlphaNumeric);
var test3 = Increment("0009", Mode.Numeric);
var test4 = Increment("zz", Mode.Alpha);
var test5 = Increment("999", Mode.Numeric);
Related
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
I am trying for the last few hours on how to parse a string with algebric notation.
For example if I have the input:
X+8X-21X+21X+16
The output should be:
9X+16
so far if I tried to see if there exists a number behind X and tried many cases, however I keep on getting an index out of bounds error, and rightufully so. Any suggestions on how to fix it?
int getXPosition= LHSString.IndexOf("X");
int noOfXs = LHSString.Split('X').Length - 1;
int XCount = 0;
if (getXPosition > -1)
{
while (XCount <= noOfXs)
{
int posX = getPositionX(s);
Regex noBeforeX = new Regex(#"\d+");
if ((posX - 1) > -1 && noBeforeX.IsMatch(LHSString.Substring(posX-1,1)))
{
string getNumber = LHSString.Substring(posX-1, 1);
sum += Convert.ToInt32(getNumber);
}
if ((posX - 2) > -1 && noBeforeX.IsMatch(LHSString.Substring(posX - 2, 1)))
{
string gotNumber = LHSString.Substring(posX - 1, 1);
int Number=Convert.ToInt32(gotNumber);
sum += Number;
}
XCount++;
s = s.Substring(posX + 1);
}
}
I would use a more maintainable approach. separate different code parts and use collection of class that will represent the "part" in the algebraic equation.
here is my suggestion:
class Program
{
static void Main(string[] args)
{
string[] operators = { "+", "-", "/", "*" };
string test = "X+8X-21X+21X+16";
int locationcounter = 0;
string part = string.Empty;
List<Part> partsList = new List<Part>();
for (int i = 0; i < test.Length; i++)
{
if (operators.Contains(test[i].ToString()))
{
var operatorbeofore = (partsList.Count <= 0 ? "" : partsList[partsList.Count - 1].OperatorAfter);
partsList.Add(new Part(part, operatorbeofore, test[i].ToString(), locationcounter));
locationcounter++;
part = string.Empty;
}
else
{
part += test[i].ToString();
}
}
// last part that remain
if (part != string.Empty)
{
partsList.Add(new Part(part, partsList[partsList.Count() - 1].OperatorAfter, "", locationcounter++));
}
// output
Console.WriteLine(GetResultOutput(partsList));
Console.ReadLine();
}
private static string GetResultOutput(List<Part> algebraicexpression)
{
// reduce all vars
var vars = algebraicexpression.Where(x => x.IsVar).OrderBy(x => x.locationInEqution).ToList();
int lastVarResult = 0;
int varResult = 0;
if (vars.Count() > 1)
{
lastVarResult = GetCalculation(vars[0].Value, vars[1].Value, vars[1].OperatorBefore);
for (int i = 2; i < vars.Count(); i++)
{
varResult = GetCalculation(lastVarResult, vars[i].Value, vars[i].OperatorBefore);
lastVarResult = varResult;
}
}
else if (vars.Count() == 1)
{
lastVarResult = vars[0].Value;
}
// calculate all "free" numbers
var numbers = algebraicexpression.Where(x => x.IsVar == false).OrderBy(x => x.locationInEqution).ToList();
int lastResult = 0;
int Result = 0;
if (numbers.Count() > 1)
{
lastResult = GetCalculation(vars[0].Value, vars[1].Value, vars[1].OperatorBefore);
for (int i = 2; i < vars.Count(); i++)
{
Result = GetCalculation(lastResult, vars[i].Value, vars[i].OperatorBefore);
lastResult = varResult;
}
}
else if (numbers.Count() == 1)
{
Result = numbers[0].Value;
}
string stringresult = string.Empty;
if (varResult != 0)
{
stringresult = varResult.ToString() + vars[0].Notation;
}
if (Result > 0)
{
stringresult = stringresult + "+" + Result.ToString();
}
else if (Result < 0)
{
stringresult = stringresult + "-" + Result.ToString();
}
return stringresult;
}
private static int GetCalculation(int x, int y, string eqoperator)
{
if (eqoperator == "+")
{
return x + y;
}
else if (eqoperator == "-")
{
return x - y;
}
else if (eqoperator == "*")
{
return x * y;
}
else if (eqoperator == "/")
{
return x / y;
}
else
{
return 0;
}
}
}
class Part
{
public string MyAlgebricPart;
public string OperatorBefore;
public string OperatorAfter;
public int locationInEqution;
public Part(string part, string operatorbefore, string operatorafter, int location)
{
this.MyAlgebricPart = part;
this.OperatorAfter = operatorafter;
this.OperatorBefore = operatorbefore;
this.locationInEqution = location;
}
public int Value
{
get
{
if (MyAlgebricPart.Count() == 1 && Notation != string.Empty)
{
return 1;
}
else
{
string result = new String(MyAlgebricPart.Where(Char.IsDigit).ToArray());
return Convert.ToInt32(result);
}
}
}
public string Notation
{
get
{
var onlyLetters = new String(MyAlgebricPart.Where(Char.IsLetter).ToArray());
if (onlyLetters != "")
{
return onlyLetters[0].ToString();
}
else
{
return string.Empty;
}
}
}
public bool IsVar
{
get
{
if (Notation == string.Empty)
return false;
else
return true;
}
}
}
So I'm building a program that takes a string and turns it into a binary number (I.E. "A" = 01000001). Then, if the user wishes, it can that binary number convert it back into a ascii character. Here the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace NDR_011
{
class Program
{
public static Byte[] BinStr(String binary)
{
var list = new List<Byte>();
for (int i = 0; i < binary.Length; i += 8)
{
String t = binary.Substring(i, 8);
list.Add(Convert.ToByte(t, 2));
}
return list.ToArray();
}
public static void Print(object mess)
{
string tmp = mess.ToString().ToUpper();
Console.Write(tmp);
}
private static List<string> buffer = new List<string>();
private static string outfile = "C:/tmp/bytes.bin";
static void Main(string[] args)
{
string tmp = "";
Print("NDR 011\n");
while (true)
{
Print(""); tmp = Console.ReadKey().Key.ToString().ToUpper();
if (Console.CursorLeft > 0)
{
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
}
if (tmp == ConsoleKey.F1.ToString())
{
break;
} else if (tmp == ConsoleKey.F2.ToString())
{
comp();
continue;
} else if (tmp == ConsoleKey.F4.ToString())
{
buffer.Clear();
continue;
} else if (tmp == ConsoleKey.F5.ToString())
{
Print("N "); string a = Console.ReadLine();
outfile = a;
continue;
} else if (tmp == ConsoleKey.F5.ToString())
{
outfile = "C:/tmp/bytes.bin";
Print("Out file reset\n");
continue;
} else if (tmp == ConsoleKey.F7.ToString())
{
//Print("N "); // string a = Console.ReadLine();
string a = "C:/tmp/bytes.bin";
string[] s = File.ReadAllText(a).Split(' ');
char[] end = new char[s.Length - 1];
for (int i=0;i<end.Length;i++)
{
end[i] = (char)BinStr(s[i])[0];
//Print(end[i]);
}
//Print((char)BinStr(s[0])[0]);
if (end[0] == 'A' && end[1] == 'D' && end[2] == 'D')
{
for (int i=0+3;i<end.Length;i++)
{
int n = end[i] + end[i];
Print(n);
}
}
//decompile(a);
continue;
}
while (tmp.Length > 1)
{
char a = tmp[tmp.Length - 1];
tmp = a.ToString();
}
buffer.Add(tmp);
}
}
static void comp()
{
if (buffer == null || buffer.Count <= 0)
{
Print("Error buffer empty");
return;
}
char[] r = new char[buffer.Count];
for (int i=0;i<buffer.Count;i++)
{
r[i] = Convert.ToChar(buffer[i]);
Print(r[i]);
}
foreach (char ch in r)
{
string a = Convert.ToString((int)ch, 2);
while (a.Length != 8)
{
string b = "0";
a = b + a;
}
File.AppendAllText(outfile, a + " ");
}
Print("Compile done!\n");
}
static void decompile(string filename)
{
}
static void run()
{
}
}
}
(the indenation got messed up when I add to this post.)
The problem is this: when I try to add the values I get from the file I get random numbers like: 100102, and odd stuff like that. What am I doing wrong? Thanks
Here's how you convert a string to a binary string of 1s and 0s:
var binstring = string.Join(" ", Encoding.ASCII.GetBytes(("Welcome, World!")).Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
To convert that back into a string, we will need to a parse byte[] array from it with a method like so:
public static byte[] GetBytes(string s)
{
byte[] result = new byte[(s.Length + 7) / 8];
int i = 0;
int j = 0;
foreach (char c in s)
{
result[i] <<= 1;
if (c == '1')
result[i] |= 1;
j++;
if (j == 8)
{
i++;
j = 0;
}
}
return result;
}
Then we get those bytes and we can simply convert it into a string using:
Encoding.ASCII.GetString(GetBytes(binstring));
References: How could I encode a string of 1s and 0s for transport?How to get the binary code behind ASCII (C#)
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;
}
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