c# StringSplitOptions.RemoveEmptyEntries not work - c#

I want to split the namelist with spaces and remove the spaces but the space is not deleted.Also, random numbers always sound the same like in the photo.
form1.cs button click codes
string[] cells;
char[] ayraclar = { ' ' };
foreach (string row in createdMailList.Items)
{
cells = row.Split(ayraclar, StringSplitOptions.RemoveEmptyEntries);
string[] isimler = new string[cells.Length];
for (int i = 0; i < cells.Length; i++)
{
string[] chars = new string[cells[i].Length];
isimler[i] = cells[i].ToString();
listBox1.Items.Add(helper.anlamliMail(isimler));
}
}
helper.cs class codes
public static string anlamliMail(string[] items)
{
string kelime ="";
var rnd = new Random();
foreach (var row in items)
{
if (!string.IsNullOrEmpty(row))
{
kelime = items[rnd.Next(0, items.Length)] + rnd.Next(0, 9999);
}
}
return kelime + "#yahoo.com";
}
createdMailList content
result :
I split the list of names with spaces, but the space is coming. that's why there are only numbers of mails

you have to create a random object once only , not each time when you call anlamliMail
var rnd = new Random();
for (int i = 0; i < cells.Length; i++)
isimler[i] = cells[i].ToString();
foreach (var item in isimler)
listBox1.Items.Add(helper.anlamliMail(rnd,isimler));
and fix anlamliMai
public static string anlamliMail(Random rnd, string[] items)
{
string kelime ="";
do
{
kelime = items[rnd.Next(0, items.Length);
}
while (! string.IsNullOrEmpty(kelime));
return kelime + rnd.Next(0, 9999).ToString() + "#yahoo.com";
}

Related

How to generate password on the following standard

I want to generate a password on the following standard.
One capital letter
10 Small letters
four numbers at the end
Code I have
//Gnerating a random password
string allowedChars = "";
allowedChars = "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,";
allowedChars += "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,";
allowedChars += "1,2,3,4,5,6,7,8,9,0,!,#,#,$,%,&,?";
char[] sep = { ',' };
string[] arr = allowedChars.Split(sep);
string passwordString = "";
string tempString = "";
int PasswordLength = 16;
Random rand = new Random();
for (int i = 0; i < Convert.ToInt32(PasswordLength); i++)
{
tempString = arr[rand.Next(0, arr.Length)];
passwordString += tempString;
}
There is no need to create both an upper and a lower value set. We have code for changing case. You could also extract the actual picking to a separate method, that would make it easier to test.
Here is my attempt:
void Main()
{
char[] lowerCase = new char[] {'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[] numbers = new char[] {'0','1','2','3','4','5','6','7','8','9'};
// Create the Random outside the method to avoid reseeding
Random random = new Random();
// Pick one char and make it uppercase
string password = PickRandomValueFromValueSet(1, lowerCase, random).ToUpper();
// Pick 10 lowercase chars
password+= PickRandomValueFromValueSet(10, lowerCase, random);
// Pick 4 digits
password+= PickRandomValueFromValueSet(4, numbers, random);
Console.Out.WriteLine.(password);
}
string PickRandomValueFromValueSet(int number, char[] valueSet, Random random)
{
string result = "";
for (int i = 0; i < number; i++)
{
result += valueSet[random.Next(0, valueSet.Length)];
}
return result;
}
I don't see why !,#,#,$,%,& and ? were allowed as numbers in the question. I have omitted those.
You need to add different chars to your password string in this way:
string lowerChars = "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[] lowerCharsArr = lowerChars.Split(sep);
string upperChars = "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[] upperCharsArr = upperChars.Split(sep);
string numbers = "1,2,3,4,5,6,7,8,9,0";
string[] numbersArr = numbers.Split(sep);
string others = "!,#,#,$,%,&,?";
string[] othersArr = others.Split(sep);
string passwordString = "";
int PasswordLength = 16;
Random rand = new Random();
passwordString += upperChars[rand.Next(0, upperChars.Length)];
for (int i = 1; i < Convert.ToInt32(PasswordLength -4); i++)
{
passwordString += lowerChars[rand.Next(0, lowerChars.Length)];
}
for (int i = 0; i < 4; i++)
{
passwordString += numbersArr[rand.Next(0, numbersArr.Length)];
}
Here's one way you could do this, optionally shuffling the result with the extension method .Shuffle, but if you really want to keep the order of upper first, then lower, then 4 digit/symbols at the end just leave that out.
namespace PasswordGen
{
public class Program
{
private static Random _random = new Random();
static void Main(string[] args)
{
var nonAlphaSymbols = "1234567890!##$%&?";
var password = new[] { (char)_random.Next('A', 'Z' + 1) } // upper case character
.Concat(Enumerable.Range(0, 10).Select(a => (char)_random.Next('a', 'z' + 1)) // 10 lower case
.Concat(Enumerable.Range(0, 4).Select(a => nonAlphaSymbols[_random.Next(0, nonAlphaSymbols.Length)]))) // 4 from nonAlpha
.Shuffle(); // optional, if you want to shuffle the outcome
Console.WriteLine(new string(password.ToArray()));
}
}
public static class Extensions
{
private static Random _random = new Random();
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> input)
{
List<T> output = new List<T>(input);
for (int i = 0; i < output.Count; i++)
{
var swapTarget = _random.Next(i, output.Count - 1);
T temp = output[swapTarget];
output[swapTarget] = output[i];
output[i] = temp;
}
return output;
}
}
}
Example: https://dotnetfiddle.net/BLOEgy

how to split string into two strings when it finds a number

So basically if I have string a = "asd333"; I want to split this string into two strings
string b = "asd" and string c = "333"
for example string a = "aaa 555";string[]b = a.Split(' '); will make
b[0]="aaa" and b[1] = "555"
But this is not what i want i want to split string into two string withouth loosing characters and split it before a number
This is my code so far
string text = textBox4.Text.ToString();
char[] whitespace = new char[] { ' ','\t' };
string[] temp = text.Split(whitespace);
But i want to change it so string[] temp equals two string first is letters and second is numbers
I think it's not the best method, but it works
string a = "aaa333aaa333aaa22bb22bb1c1c1c";
List<string> result = new List<string>();
int lastSplitInedx = 0;
for (int i = 0; i < a.Length-1; i++)
{
if (char.IsLetter(a[i]) != char.IsLetter(a[i + 1]))
{
result.Add(a.Substring(lastSplitInedx, (i + 1) - lastSplitInedx));
lastSplitInedx = i+1;
}
if (i+1 == a.Length-1)
{
result.Add(a.Substring(lastSplitInedx));
}
}
foreach (string s in result)
{
Console.WriteLine(s);
}
Get the matched group from index 1 and 2.
String literals for use in programs:
C#
#"(\D+)\s*(\d+)"
Search for the integer in the string and split the string at that position
string a = "str123";
string b = string.Empty;
int val;
for (int i=0; i< a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}
if (b.Length>0)
val = int.Parse(b);

How to check if file contains strings, which will double repeat sign?

I would like to check if file containing some strings, separated with # contains double repeat sign. Example:
I have a file like this:
1234#224859#123567
I am reading this file and putting strings separated with # it into array.
I would like to find which strings have a digit repeated next to each other (in this case 224859) and return position of first digit that repeats in this string?
This is what I have so far:
ArrayList list = new ArrayList();
OpenFileDialog openFile1 = new OpenFileDialog();
int size = -1;
DialogResult dr = openFile1.ShowDialog();
string file = openFile1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
string temp = "";
for (int i = 0; i < text.Length; i++)
{
if (text[i] != '#')
{
temp += text[i].ToString();
}
else
{
list.Add(temp);
temp = "";
}
}
}
catch (IOException)
{
}
string all_values = "";
foreach (Object obj in list)
{
all_values += obj.ToString() + " => ";
Console.WriteLine(" => ", obj);
}
textBox1.Text = (all_values);
This regex should do the trick.
var subject = "1234#224859#123567";
foreach(var item in subject.Split('#'))
{
var regex = new Regex(#"(?<grp>\d)\k<grp>");
var match =regex.Match(item);
if(match.Success)
{
Console.WriteLine("Index : {0}, Item:{1}", match.Index, item);
//prints Index : 0, Item:224859
}
}
This is a more procedural approach than Sriram's, but the main benefit is remembering your results in order to use them later in your program.
Basically, the string is split based on the # delimiter, which returns a string[] which holds each number inside. Then, for each string you iterate through the characters and check to see if the current character at i matches the next character at i + 1. If so, the earliest appearance of a duplicate digit is at i, so i is remembered and we break out of the loop that processes chars.
Since int is a non-nullable type, I decided to use -1 to indicate that a match was not found in a string.
Dictionary<string, int> results = new Dictionary<string, int>();
string text = "1234#224859#123567#11#4322#43#155";
string[] list = text.Split('#');
foreach (string s in list)
{
int tempResult = -1;
for (int i = 0; i < s.Length - 1; i++)
{
if(s.ElementAt(i) == s.ElementAt(i + 1))
{
tempResult = i;
break;
}
}
results.Add(s, tempResult);
}
foreach (KeyValuePair<string, int> pair in results)
{
Console.WriteLine(pair.Key + ": " + pair.Value);
}
Output:
1234: -1
224859: 0
123567: -1
11: 0
4322: 2
43: -1
155: 1
here's another Regex that works
int indexof = -1;
String input = "3492883#32280948093284#990303294";
string[] numbers = input.Split('#');
foreach(string n in numbers)
{
Match m=Regex.Match(n, #"(\d)\1+");
if (m.Success)
{
indexof = m.Index;
}
}
Would this do what you are looking for?
string text = File.ReadAllText(file);
string[] list = text.Split(new char[] { '#' });
Then, after you have the strings separated:
foreach (string s in list)
{
int pos = HasDoubleCharacter(s);
if (pos > -1)
{
// do something
}
}
private static int HasDoubleCharacter(string text)
{
int pos = 0;
char[] c3 = text.ToCharArray();
char lastChar = (char)0;
foreach (char c in c3)
{
if (lastChar == c)
return pos;
lastChar = c;
pos++;
}
return -1;
}
Or are you just looking for the list of positions of all doubles in the original text. If so (and you don't need to act on the various strings separately, you might try this:
private static List<int> FindAllDoublePositions(string text)
{
List<int> positions = new List<int>();
char[] ca = text.ToCharArray();
char lastChar = (char)0;
for (int pos = 0; pos < ca.Length; pos++)
{
if (Char.IsNumber(ca[pos]) && lastChar == ca[pos])
positions.Add(pos);
lastChar = ca[pos];
}
return positions;
}
If your looking for a specific string pattern, Regex is most likely to be your best friend :
string text = "1234#224859#123567asdashjehqwjk4234#244859#123567asdhajksdhqjkw1434#244859#123567";
var results = Regex.Matches(text, #"\d{4}#(?<Value>\d{6})#\d{4}");
var allValues = "";
foreach (Match result in results)
{
allValues = result.Groups["Value"].Value + " => ";
Console.WriteLine(" => ", result.Value);
}

Find repeated count from input data stream...

I have tried several time but couldn’t find the way to solve my problem. Here my txt file shown in below.
695
748
555
695
748
852
639
748
I put the for loop to read the data and put them in to array. So now I want to filter repeat numbers from the input txt data. How can I have a count of repeated data.
static void Main(string[] args)
{
int x = 0;
int count = 0;
String[] line = File.ReadAllLines("C:/num.txt");
int n = line.Length;
String[] res = new String[n];
for (int i = 0; i < n; i++)
{
res[i] = line[i].Substring(x,x+8);
Console.WriteLine(res[i]);
}
Console.ReadLine();
}
You use GroupBy()
var result = res.GroupBy(x => x);
foreach(var g in result)
{
Console.WriteLine(g.Key + " count: " + g.Count());
}
Somehow you have to keep track of things you have seen before.
One way to do that is to place the numbers in a list the first time you see them. If a given number is already in the list, filter it out on the latter occurrences.
Here's an example with the list. Note that your code to fetch a substring of the input crashes.
static void Main(string[] args)
{
int x = 0;
int count = 0;
String[] line = new string[] { "123", "456", "123" }; //File.ReadAllLines("C:/num.txt");
int n = line.Length;
String[] res = new String[n];
List<string> observedValues = new List<string>();
for (int i = 0; i < n; i++)
{
string consider = line[i]; // This code crashes: .Substring(x, x + 8);
if (!observedValues.Contains(consider))
{
observedValues.Add(consider);
res[i] = consider;
Console.WriteLine(res[i]);
}
else
{
Console.WriteLine("Skipped value: " + consider + " on line " + i);
}
Console.ReadLine();
}
}
Another method is to pre-sort the input so that duplicates are adjacent.
Example:
(Note, you may want to remove white space in the input prior to sorting. Leading white space will break this code).
static void Main(string[] args)
{
int x = 0;
int count = 0;
String[] line = new string[] { "123", "456", "123" }; //File.ReadAllLines("C:/num.txt");
int n = line.Length;
String[] res = new String[n];
string previous = null;
Array.Sort(line); // Ensures that equal values are adjacent
for (int i = 0; i < n; i++)
{
string consider = line[i].Trim(); // Note leading whitespace will break this.
if (consider != previous)
{
previous = consider;
res[i] = consider;
Console.WriteLine(res[i]);
}
else
{
Console.WriteLine("Skipped value: " + consider + " on line " + i);
}
Console.ReadLine();
}
}
So now I want to filter repeat numbers from the input txt data.
if all you need is filter out duplicates you can use this:
String[] line = File.ReadAllLines("C:/num.txt");
var filteredLines = line.Distinct();
foreach (var item in filteredLines)
Console.WriteLine(item);

Function that generates strings according to input

I need a C# function that takes 2 strings as an input and return an array of all possible combinations of strings.
private string[] FunctionName(string string1, string string2)
{
//code
}
The strings input will be in the following format:
string1: basement
string2: a*fa
Now what I need is all combinations of possible strings using the characters in String2 (ignoring the * symbols), and keeping them in the same character position like this:
baaement, baaefent, baaefena, basefent, basemena, etc.
EDIT:
This is not homework. I need this function for a piece of a program I am doing.
The following is the code I have so far but it has some bugs.
static List<string> combinations = new List<string>();
static void Main(string[] args)
{
//include trimming of input string
string FoundRes = "incoming";
string AltRes = "*2*45*78";
List<int> loc = new List<int>();
string word = "";
for (int i = 0; i < AltRes.Length; i++)
{
if (AltRes[i] != '*')
{
loc.Add(i);
word += AltRes[i];
}
}
generate(word);
string[] aaa = InsertSymbol(FoundRes, loc.ToArray(), AltRes, combinations);
Console.WriteLine("input string: " + FoundRes);
Console.WriteLine("Substitute string: " + AltRes);
Console.WriteLine("============Output============");
for (int j = 0; j < aaa.Length; j++)
{
Console.WriteLine(aaa[j]);
}
Console.ReadKey();
}//
private static void generate(string word)
{
// Add this word to combination results set
if (!combinations.Contains(word))
combinations.Add(word);
// If the word has only one character, break the recursion
if (word.Length == 1)
{
if (!combinations.Contains(word))
combinations.Add(word);
return;
}
// Go through every position of the word
for (int i = 0; i < word.Length; i++)
{
// Remove the character at the current position
// call this method with the String
generate(word.Substring(0, i) + word.Substring(i + 1));
}
}//
private static string[] InsertSymbol(string orig, int[] loc, string alternative, List<string> Chars)
{
List<string> CombinationsList = new List<string>();
string temp = "";
for (int i = 0; i < Chars.Count; i++)
{
temp = orig;
for (int j = 0; j < Chars[i].Length; j++)
{
string token = Chars[i];
if (alternative.IndexOf(token[j]) == loc[j])
{
temp = temp.Remove(loc[j], 1);
temp = temp.Insert(loc[j], token[j].ToString());
// int pos = sourceSubst.IndexOf(token[j]);
// sourceSubst = sourceSubst.Remove(pos, 1);
// sourceSubst = sourceSubst.Insert(pos, ".");
}
else
{
temp = temp.Remove(alternative.IndexOf(token[j]), 1);
temp = temp.Insert(alternative.IndexOf(token[j]), token[j].ToString());
}
}
CombinationsList.Add(temp);
}
return CombinationsList.ToArray();
}//
It does sound like homework. As a suggestion, I would ignore the first parameter and focus on getting all possible permutations of the second string. What's turned off, what's turned on, etc. From that list, you can easily come up with a method of swapping out characters of the first string.
On that note, I'm in the uncomfortable position of having a function ready to go but not wanting to post it because of the homework implication. I'd sure love for somebody to review it, though! And technically, there's two functions involved because I just happened to already have a generic function to generate subsets lying around.
Edit: OP says it isn't homework, so here is what I came up with. It has been refactored a bit since the claim of two functions, and I'm more than open to criticism.
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main()
{
string original = "phenomenal";
string pattern = "*xo**q*t**";
string[] replacements = StringUtility.GetReplacementStrings(original, pattern, true);
foreach (string replacement in replacements)
Console.WriteLine(replacement);
Console.Read();
}
public static class StringUtility
{
public static string[] GetReplacementStrings(string original, string pattern, bool includeOriginal)
{
// pattern and original might not be same length
int maxIndex = Math.Max(original.Length, pattern.Length);
List<int> positions = GetPatternPositions(pattern, maxIndex, '*');
List<int[]> subsets = ArrayUtility.CreateSubsets(positions.ToArray());
List<string> replacements = GenerateReplacements(original, pattern, subsets);
if (includeOriginal)
replacements.Insert(0, original);
return replacements.ToArray();
}
private static List<string> GenerateReplacements(string original, string pattern, List<int[]> subsets)
{
List<string> replacements = new List<string>();
char[] temp = new char[original.Length];
foreach (int[] subset in subsets)
{
original.CopyTo(0, temp, 0, original.Length);
foreach (int index in subset)
{
temp[index] = pattern[index];
}
replacements.Add(new string(temp));
}
return replacements;
}
private static List<int> GetPatternPositions(string pattern, int maxIndex, char excludeCharacter)
{
List<int> positions = new List<int>();
for (int i = 0; i < maxIndex; i++)
{
if (pattern[i] != excludeCharacter)
positions.Add(i);
}
return positions;
}
}
public static class ArrayUtility
{
public static List<T[]> CreateSubsets<T>(T[] originalArray)
{
List<T[]> subsets = new List<T[]>();
for (int i = 0; i < originalArray.Length; i++)
{
int subsetCount = subsets.Count;
subsets.Add(new T[] { originalArray[i] });
for (int j = 0; j < subsetCount; j++)
{
T[] newSubset = new T[subsets[j].Length + 1];
subsets[j].CopyTo(newSubset, 0);
newSubset[newSubset.Length - 1] = originalArray[i];
subsets.Add(newSubset);
}
}
return subsets;
}
}
}
since it's hopw work I'd only suggest some way to solve the problem rather than writing the code.
if you loop the second parameter every time you hit a letter you'll have to options either use the letter from the first argument or the letter from the second. collect all these optins together with the index. keep a list of the parts from the first argument that will never change. iterate thorugh those two lists to created all the possible permutations
Decimal to Binary converted code is stolon copied from here.
static void Main()
{
string string1 = "basement";
string string2 = "**a*f**a";
string[] result = GetCombinations(string1, string2);
foreach (var item in result)
{
Console.WriteLine(item);
}
}
private static string[] GetCombinations(string string1, string string2)
{
var list = new List<List<char>> { new List<char>(), new List<char>() };
var cl = new List<char>();
List<string> result = new List<string>();
for (int i = 0; i < string1.Length; i++)
{
if (string2[i] == '*')
{
cl.Add(string1[i]);
}
else
{
list[0].Add(string1[i]);
list[1].Add(string2[i]);
}
}
int l = list[0].Count;
for (int i = 0; i < (Int64)Math.Pow(2.0,l); i++)
{
string s = ToBinary(i, l);
string ss = "";
int x = 0;
int y = 0;
for (int I = 0; I < string1.Length; I++)
{
if (string2[I] == '*')
{
ss += cl[x].ToString();
x++;
}
else
{
ss += (list[int.Parse(s[y].ToString())][y]);
y++;
}
}
result.Add(ss);
}
return result.ToArray<string>();
}
public static string ToBinary(Int64 Decimal, int width)
{
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
var d = width - BinaryResult.Length;
if (d != 0) for (int i = 0; i < d; i++) BinaryResult = "0" + BinaryResult;
return BinaryResult;
}
which password cracker do you want to program? :)
how about
if string2 contains '*'
foreach(char ch in string1)
replace first * with ch,
execute FunctionName
else
print string2

Categories

Resources