How do I get all alpha-number combo's in a given alpha-number combo range using c#?
For getting all numbers in a range I'll do something like below
int x = 10;
int y = 15;
int z=y-x+1;
var range =Enumerable.Range(x,z);
foreach (var element in range)
{
Console.WriteLine(element.ToString()+"-->"+x.ToString()+"-"+y.ToString());
}
Console.ReadLine();
But when the value of x is like 1x and y is like 2b how do I get the range of strings like below?
1x
1y
1z
2a
2b
First, parse the string to get the numerical value and the character. Then, loop for each number from the start to the end. Inside, loop for each character in the alphabet from the start to the current end.
Here you go:
string x = "1x";
string y = "2b";
char startCharacter = x.Substring(x.Length-1)[0];
char endCharacter = y.Substring(y.Length-1)[0];
int startNumber = int.Parse(x.Substring(0, x.Length - 1));
int endNumber = int.Parse(y.Substring(0, y.Length - 1));
var range = new List<string>();
string alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i = startNumber; i <= endNumber; ++i) {
int currentCharEnd = (i == endNumber) ? alphabet.IndexOf(endCharacter) : alphabet.Length - 1;
for(int j = alphabet.IndexOf(startCharacter); j <= currentCharEnd; ++j) {
range.Add(i.ToString() + alphabet[j]);
}
startCharacter = 'a';
}
// range is now { "1x", "1y", "1z", "2a", "2b" }
You can start by doing this, and extend it to achieve your task fully.
string[] abc = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
string x = "1g";
string y = "2b";
string strx = Regex.Match(x, #"\d+").Value;
string stra = Regex.Match(x, #"[a-z]+").Value;
int intx = Int32.Parse(strx);
string stry = Regex.Match(y, #"\d+").Value;
string strb = Regex.Match(x, #"[a-z]+").Value;
int inty = Int32.Parse(stry);
Console.WriteLine(strx);
Console.WriteLine(stra);
Console.WriteLine("----");
int len = inty - intx + 1;
List<string> xycombinations = new List<string>();
string[] ycombinations = new string[] { };
if (len >= 0)
{
int starting = 0;
while (abc[starting] != stra)
{
starting = starting + 1;
}
while (starting < abc.Length)
{
xycombinations.Add(intx.ToString() + abc[starting]);
starting = starting + 1;
}
for (int i = 0; i < xycombinations.Count; i++)
{
Console.WriteLine(xycombinations[i]);
}
}
Console.ReadLine();
It only makes the combination of string x till the end, for instance string x is "1g", so this code makes combinations 1g, 1h, 1i, ij. Similarly you can make combinations of string y by extending. Hope it helps you.
Related
I am trying to see weather the string is in alphabetical order or no and this error pops up
System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length
at System.String.Substring(Int32 startIndex, Int32 length)
at Rextester.Program.Main(String[] args)**
public static void Main(string[] args)
{
string str = "bat\ncat\ndog\n";
int c = 0;
for (int i = 0; i < str.Length; i++)
{
if ((str.Substring(i,i + 1).Equals("\n")))
{
c++;
}
}
String[] strArray = new String[c + 1]; //declare with size
int g = 0;
String h = "";
for (int i = 0; i < str.Length; i++)
{
if ((str.Substring(i,i + 1).Equals("\n")))
{
strArray[g] = h;
h = "";
g = g + 1;
}
else
{
h = h + str.Substring(i,i + 1);
}
}
String p = "True";
for (int i = 0; i < g; i++)
{
if (i < (g - 1))
{
String f = strArray[i];
String g2 = strArray[i + 1];
char d = f[0];
char s = g2[0];
int d1 = (int)d;
int s1 = (int)s;
if (d1 > s1)
{
p = "False";
}
}
}
Console.WriteLine(p);
}
}
Not sure about what you are doing in your second loop and why is it so complex. We can do the same like this. Hope this helps.
using System;
public class Program
{
public static void Main()
{
string str = "abcd";
str = str.Replace('\n',' ');
String p = "True";
for (int i = 1; i < str.Length; i++) {
// if element at index 'i' is less
// than the element at index 'i-1'
// then the string is not sorted
if (str[i] < str[i - 1]) {
p = "false";
}
}
Console.WriteLine(p);
}
}
Pay attention to the definition of substring
The substring starts at a specified character position and has a
specified length
Considering your first use of substring, here
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, i + 1).Equals("\n"))
{
c++;
}
}
What happens when we get to i=6 here? Substring tries to give you a new string that starts at position i = 6, and is length = 7 characters long. So it tries to give you 7 characters starting from str[6] to str[12]. Well, there is no str[12], so you get an exception.
Its clear that your intent is NOT to get a string that starts at position 6 and is 7 characters long. You want ONE character, so your loop should be this
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, 1).Equals("\n"))
{
c++;
}
}
But theres a much simpler way to get your words in alphabetical order using LINQ
string str = "bat\ncat\ndog\n";
//Removes the trailing \n so you don't have one entry that is only whitespace
str = str.Trim();
string[] strSplit = str.Split('\n').OrderBy(x => x[0]).ToArray();
Now all substrings are sorted alphabetically and you can do whatever you want with them
My input is:
something1#email.com.;;
something2#email.eu,./
something3#email.org..
something4#email.netcdsfsd
What I want is to get rid of all characters after my "domains"(stored in array).
So output should be:
something1#email.com
something2#email.eu
something3#email.org
something4#email.net
My code is:
string[] domains = richTextBox_domains.Text.Split(';');
char[] specialchars = ".!#$%^&*()-_=+[]{}\\|;:'\",.<>/?".ToCharArray();
for (int x = 0; x < domains.Length; x++)
{
for (int y = 0; y < specialchars.Length; y++)
{
string check = domains[x] + specialchars[y];
string aftertmp = "." + after.Substring(after.IndexOf('.') + 1);
if (aftertmp == check)
after = after.Replace(check, domains[x]);
}
}
It's working but not always and only for one character at the end.
I will be glad for help
use regex to check email id and than store it in different array
var regex1 = new Regex("(([-a-zA-Z0-9])|([-a-zA-Z0-9]{1,256}[#%._\+~#=][-a-zA-Z0-9])){1,10}\.[-a-zA-Z0-9]{1,10}\b",RegexOptions.IgnoreCase);
string[] domains = richTextBox_domains.Text.Split(';');
List<string> l = new List<string>();
for (int x = 0; x < domains.Length; x++)
{
var results = regex1.Matches(domains[x]);
foreach (Match match in results)
{
l.Add(match.Groups[1].Value);
MessageBox.Show(match.Groups[1].Value);
}
}
string[] s = l.ToArray();// new array
hope this helps
This works fine
string[] s = { ".com",".net",".edu",".eu" };
string[] domain = new string[]
{
"something1#email.com.;;",
"something2#email.eu,./",
"something3#email.org..",
"something4#email.netcdsfsd"
};
string result = "";
for (int m = 0; m < domain.Length; m++)
{
for (int i = 0; i < s.Length; i++)
{
if (domain[m].IndexOf(s[i]) != -1)
{
result = domain[m].Substring(0, domain[m].IndexOf(s[i])) + s[i];
MessageBox.Show(result);
}
}
}
}
I've written a code that has a list and I want to sort the list alphabetically and numerically.
For example the first items in the list are
list[0] = "INPUT 10"
list[1] = "INPUT 5".
I want my list reorganized like this:
list[0] = "INPUT 5"
list[1] = "INPUT 10".
So basically my program gets checked items from a checked list box,stores them in a list, and I want it to reorganize the list alphabettically.
The checked list box has items like INPUT 1,INPUT 2,INPUT 3...and so fourth. Can anyone suggest me a way of how to go about this?
UPDATED CODE
I've updated my code and now this code splits the strings into INPUT and 10.The "q" list obtains the checked items in the input box,the string "s" array gets the splittd data from the q list. Then the "numbers" list gets only the number part of the string for example "INPUT 5",the number list will only get "5".Then I want to sort these numbers and build another string combining the sorted number list and the string "INPUT" and add it to the output checkedlistbox. My code isnt working though...any suggestions?It should sort the numbers but it doesnt...anyone have any suggestions of why this code isnt working? And I keep on getting error messages of the array being able to unhandle negative integers and what not.
List<string> q = new List<string>();
List<string> numbers = new List<string>();
private void button_ekle_Click(object sender, EventArgs e)
{
for (int k = clb_input.Items.Count - 1; k >= 0; k--)
{
if (clb_input.GetItemChecked(k) == true)
{
q.Add(clb_input.Items[k].ToString());
//clb_output.Items.Add(clb_input.Items[k]);
clb_input.Items.RemoveAt(k);
}
else { }
}
string[] s = new string[q.Count * 2];
//string[] numbers=new string[q.Count/2];
for (int t = 1; t <= q.Count * 2; t++)
{
if (q != null)
s = q[t - 1].ToString().Split(' ');
else { s[t] = null; }
}
for (int x = 1; x <= q.Count; x++)
{
if (s[2 * x - 1] != null)
{
numbers[x - 1] = s[2 * x - 1];
numbers.Sort();
clb_output.Items.Add("INPUT "+ numbers[x - 1].ToString());
}
else { numbers[x - 1] = null; }
}
}
What you need is Alphanumeric Sorting ( most commonly seen in windows explorer, the way files are sorted)
Code can be found here : http://www.dotnetperls.com/alphanumeric-sorting
Sample
class Program
{
static void Main()
{
string[] highways = new string[]
{
"100F",
"50F",
"SR100",
"SR9"
};
//
// We want to sort a string array called highways in an
// alphanumeric way. Call the static Array.Sort method.
//
Array.Sort(highways, new AlphanumComparatorFast());
//
// Display the results
//
foreach (string h in highways)
{
Console.WriteLine(h);
}
}
}
Output
50F
100F
SR9
SR100
Implementation
public class AlphanumComparatorFast : IComparer
{
public int Compare(object x, object y)
{
string s1 = x as string;
if (s1 == null)
{
return 0;
}
string s2 = y as string;
if (s2 == null)
{
return 0;
}
int len1 = s1.Length;
int len2 = s2.Length;
int marker1 = 0;
int marker2 = 0;
// Walk through two the strings with two markers.
while (marker1 < len1 && marker2 < len2)
{
char ch1 = s1[marker1];
char ch2 = s2[marker2];
// Some buffers we can build up characters in for each chunk.
char[] space1 = new char[len1];
int loc1 = 0;
char[] space2 = new char[len2];
int loc2 = 0;
// Walk through all following characters that are digits or
// characters in BOTH strings starting at the appropriate marker.
// Collect char arrays.
do
{
space1[loc1++] = ch1;
marker1++;
if (marker1 < len1)
{
ch1 = s1[marker1];
}
else
{
break;
}
} while (char.IsDigit(ch1) == char.IsDigit(space1[0]));
do
{
space2[loc2++] = ch2;
marker2++;
if (marker2 < len2)
{
ch2 = s2[marker2];
}
else
{
break;
}
} while (char.IsDigit(ch2) == char.IsDigit(space2[0]));
// If we have collected numbers, compare them numerically.
// Otherwise, if we have strings, compare them alphabetically.
string str1 = new string(space1);
string str2 = new string(space2);
int result;
if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
{
int thisNumericChunk = int.Parse(str1);
int thatNumericChunk = int.Parse(str2);
result = thisNumericChunk.CompareTo(thatNumericChunk);
}
else
{
result = str1.CompareTo(str2);
}
if (result != 0)
{
return result;
}
}
return len1 - len2;
}
}
The simplest solution is to just left-pad the numerical values with a space to the same length.
List<string> lst = new List<string>
{
"Item 9",
"Item 999",
"Thing 999",
"Thing 5",
"Thing 1",
"Item 20",
"Item 10",
};
lst.Sort();
Output:
Item 9
Item 10
Item 20
Item 999
Thing 1
Thing 5
Thing 999
And you can always remove the extra white space used for padding after the sorting operation is performed.
You can use Sort with a Comparer like this:
List<string> q = new List<string>();
private void button_ekle_Click(object sender, EventArgs e)
{
for (int k=clb_input.Items.Count-1; k >= 0; k--)
{
if (clb_input.GetItemChecked(k) == true)
{
q.Add(clb_input.Items[k].ToString());
clb_input.Items.RemoveAt(k);
}
else { }
}
q.Sort((p1,p2)=>((int)(p1.split(" ")[1])).CompareTo((int)(p2.split(" ")[1])));
for (int t = 0; t < q.Count; t++)
{
clb_output.Items.Add(q[t].ToString());
}
}
I'm new to C#. I have a short form and a long form of a client code. The short form is some alpha characters and some numeric ones (ABC12), while the long form is always 15 characters long with the space between the alpha and the numeric parts padded out with zeros (ABC000000000012). I need to be able to convert from the short form to the long. The code below is how I've got it to work - is this the best way to do this?
public string ExpandCode(string s)
{
// s = "ABC12"
int i = 0;
char c;
bool foundDigit = false;
string o = null;
while (foundDigit == false)
{
c = Convert.ToChar(s.Substring(i, 1));
if (Char.IsDigit(c))
{
foundDigit = true;
o = s.Substring(0, i) + new String('0', 15-s.Length) + s.Substring(i,s.Length-i);
}
i += 1;
}
return (o); //o = "ABC000000000012"
}
Your code is basically correct, however it could be slow, since String.Substring(...) creates a new string every time called.
I also suggest that you use the built-in functions of the .NET api for accomplishing your tasks, which can make coding easier a lot:
private char[] numbers = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
public string ExpandCode(string s)
{
//Find the first numeric char.
int index = s.IndexOfAny(numbers);
//Insert zeros and return the result.
return s.Insert(index, new String('0', 15 - s.Length));
}
Take a look at this:
public string ExpandCode(string s)
{
var builder = new StringBuilder(s);
var index = Array.FindIndex(s.ToArray(), x => char.IsDigit(x));
while (builder.Length < 15)
{
builder.Insert(index, '0');
}
return builder.ToString();
}
I assume that string are always letter -> digit (like "abc123" or "ab1234").
The purer, the faster
public static string ExpandCode4(string s)
{
char[] res = new char[15];
int ind = 0;
for (int i = 0; i < s.Length && s[i] >= 'A'; i++)
res[ind++] = s[i];
int tillDigit = ind;
for (int i = 0; i < 15 - s.Length; i++)
res[ind++] = '0';
for (int i = 0; i < s.Length - tillDigit; i++)
res[ind++] = s[tillDigit + i];
return new string(res);
}
Benchmark for all the answers is as follows,
internal class Program
{
private static void Main(string[] args)
{
var inputs = new List<string>();
for (int i = 0; i < 10000000; i++)
{
inputs.Add("ABC1234");
}
var n1 = DateTime.Now;
inputs.ForEach(i => ExpandCode1(i));
var r1 = (DateTime.Now - n1).Ticks;
var n2 = DateTime.Now;
inputs.ForEach(i => ExpandCode2(i));
var r2 = (DateTime.Now - n2).Ticks;
var n3 = DateTime.Now;
inputs.ForEach(i => ExpandCode3(i));
var r3 = (DateTime.Now - n3).Ticks;
var n4 = DateTime.Now;
inputs.ForEach(i => ExpandCode4(i));
var r4 = (DateTime.Now - n4).Ticks;
var results = new List<Result>()
{
new Result() {Name = "1", Ticks = r1},
new Result() {Name = "2", Ticks = r2},
new Result() {Name = "3", Ticks = r3},
new Result() {Name = "4", Ticks = r4}
};
results.OrderBy(r => r.Ticks).ToList().ForEach(Console.WriteLine);
Console.ReadKey();
}
public static string ExpandCode4(string s)
{
char[] res = new char[15];
int ind = 0;
for (int i = 0; i < s.Length && s[i] >= 'A'; i++)
res[ind++] = s[i];
int tillDigit = ind;
for (int i = 0; i < 15 - s.Length; i++)
res[ind++] = '0';
for (int i = 0; i < s.Length - tillDigit; i++)
res[ind++] = s[tillDigit + i];
return new string(res);
}
public static string ExpandCode1(string s)
{
char[] numbers = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
//Find the first numeric char.
int index = s.IndexOfAny(numbers);
//Insert zeros and return the result.
return s.Insert(index, new String('0', 15 - s.Length));
}
public static string ExpandCode2(string s)
{
var builder = new StringBuilder(s);
var index = Array.FindIndex(s.ToArray(), x => char.IsDigit(x));
while (builder.Length < 15)
{
builder.Insert(index, '0');
}
return builder.ToString();
}
public static string ExpandCode3(string s)
{
var match = Regex.Match(s, #"([^\d]+)(\d+)");
var letters = match.Groups[1].Value;
var numbers = int.Parse(match.Groups[2].Value);
var formatString = "{0}{1:d" + (15 - letters.Length) + "}";
var longForm = string.Format(formatString, letters, numbers);
return longForm;
}
}
public class Result
{
public long Ticks { get; set; }
public string Name { get; set; }
public override string ToString()
{
return Name + " - " + Ticks;
}
}
You can use string.Format() to take care of the padding for you. I used regex (and not in a very robust manner) to parse out the letters and numbers but you may be able to do this more efficiently another way.
The key point is that we dynamically figure out how many zero's we need, and then use a format string of the form X:dY where X = format ordinal and Y = the number of zeros you wish to pad.
var match = Regex.Match("ABC12", #"([^\d]+)(\d+)");
var letters = match.Groups[1].Value;
var numbers = int.Parse(match.Groups[2].Value);
var formatString = "{0}{1:d" + (15 - letters.Length) + "}";
var longForm = string.Format(formatString, letters, numbers);
string[] myString = {"a","b","c","d"}
//Reverse string algorithm here
myString = {"d","c","b","a"}
I have been asked to do so in an interview without the help of any temporary variable or .NET class, string methods, etc to reverse the elements of the same string array. I was told to use basic programming constructs like loops. Since, I am up for another interview today, I am in a hurry to know whether this is actually possible because I could not find a solution to this.
Here you go, no support variables, no .net functions :) But it makes the assumptions that all the strings in the array have length 1 ( as they do in the code you posted).
string[] myString = {"a","b","c","d", "e"};
for(int i = 0; i < myString.Length/2; i++)
{
myString[i] += myString[myString.Length -1 -i];
myString[myString.Length -1 -i] = ""+myString[i][0];
myString[i] = "" + myString[i][1];
}
Since you cannot use a temporary variable, the best I can think of is appending the strings first and then removing the appended part again:
// append last strings to first strings
for(int i = 0; i < myString.Length / 2; i++)
{
myString[i] = myString[i] + myString[myString.Length - i - 1];
}
// copy first half to last half
for(int i = myString.Length / 2 + 1; i < myString.Length; i++)
{
myString[i] = myString[myString.Length - i - 1]
.SubString(0,
myString[myString.Length - i - 1].Length
- myString[i].Length);
}
// remove useless part from first half
for(int i = 0; i < myString.Length / 2; i++)
{
myString[i] = myString[i].SubString(
myString[myString.Length - i - 1].Length
- myString[i].Length);
}
Stupid approach? Yes. But no additional variables are involved.
string[] myString = {"a","b","c","d"}
for(int = (myString.Length - 1); int >= 0; i--) {
string rev = myString[i];
Console.Write(rev);
}
Sorry I posted a wrong answer... here's the verified one:
int k = len - 1;
for(int i = 0; i<len/2; i++)
{
myString[i] = myString[i]+"."+myString[k--];
}
for(int i = len/2; i<len; i++)
{
myString[i] = myString[k].substring(0, 1);
myString[k] = myString[k--].substring(2,3);
}
However, just consider this a pseudo-code... I did not check for .NET syntax.
The right answer in your interview is "Why would you NOT use the class libraries?" But then say, "Well if I needed to write a customized method because the libraries don't support the need...". Then I would show both methods and argue when to use each method. If they had a problem with this explanation then I wouldn't want to work there anyway.
With Libraries:
string[] myString = {"a","b","c","d"};
List<string> list = myString.ToList();
list.Reverse();
myString = list.ToArray();
Without:
string[] myString = {"a","b","c","d"};
string[] newString = new string[myString.Length];
for (int i = 0, j = myString.Length - 1; i < myString.Length && j >= 0; i++, j--)
{
newString[j] = myString[i];
}
myString = newString;
This is not a complete answer, perhaps an idea..
It is possible to swap two numbers by mathematics
swap(a,b)
a = a + b
b = a - b
a = a - b
Initially I was going to suggest this can be done with character ascii values.. Then I noticed the strings.
Is it acceptable then to
swap(str1, str2)
str1 = str1+str2
str2 = str1[0]
str1 = str1[1]
I hope you get the idea
Have you tried this
string[] myString = { "a", "b", "c", "d","e","f" };
int _firstcounter = 0;
int _lastcounter = myString.Length-1;
while (_firstcounter<=_lastcounter)
{
myString[_firstcounter] += myString[_lastcounter];
myString[_lastcounter] = "" + myString[_firstcounter][0];
myString[_firstcounter] = "" + myString[_firstcounter][1];
_firstcounter++;
_lastcounter--;
}
If the maximum string length is of array is less than 10, then is might be helpful....
string[] myString = { "aaaa", "bbb", "ccccccc", "dddddd", "e", "fffffffff" };
for (int i = 0; i < myString.Length; i++)
{
myString[i] = myString[i].Length.ToString() + myString[i];
}
for (int i = 0; i < myString.Length/2; i++)
{
myString[i] = myString[i] + myString[myString.Length-1-i];
myString[myString.Length - 1 - i] = myString[i];
}
for (int i = 0; i < myString.Length/2; i++)
{
myString[i] = myString[i].Substring(int.Parse(myString[i][0].ToString())+2,int.Parse(myString[i][int.Parse(myString[i][0].ToString())+1].ToString()));
}
for (int i = myString.Length / 2; i < myString.Length; i++)
{
myString[i] = myString[i].Substring(1, int.Parse(myString[i][0].ToString()));
}
Try this.
public static class ExtensionMethods
{
public static IEnumerable<T> ReverseArray<T>(this T[] source)
{
for (int i = source.Length - 1; i >= 0; i--)
{
yield return source[i];
}
}
public static T[] EnumerableToArray<T>(this IEnumerable<T> source)
{
var array = new T[source.Count()];
int k = 0;
foreach (var n in source)
{
array[k++] = n;
}
return array;
}
}
Example usage
public static void Main(string[] args)
{
string[] myString = {"a", "b", "c", "d"};
myString = myString.ReverseArray().EnumerableToArray();
}
static void ReverseMyString(string[] myString)
{
int start=0, end= myString.Length-1;
string temp = "";
while (start < end)
{
temp = myString[start];
myString[start] = myString[end];
myString[end] = temp;
start++;
end--;
}
}
Yes you can do it-
string[] myString = { "a", "b", "c", "d" };
myString = (from a in myString orderby a descending select a).ToArray();
You need at least one variable to swap values.
In pseudo code:
for(i : 0..n/2) {
// swap s[i] and s[n-i]
String tmp = s[i];
s[i] = s[n-i];
s[n-i] = tmp;
}
We Can use Array.Reverse(UrArray);
Check out Array.Reverse method on MSDN.