check if string contains dictionary Key -> remove key and add value - c#

I am stuck at a function which checks a string ('14534000000875e') if it contains a letter.
If it contains a letter (a-z), remove the letter and add a string to the end.
To realize this, I have created a Dictionary<char, string> Pairs which has mapped a to 09001, b to 09002 [...] and z to 09026
This is my code so far:
public static string AlterSerial(string source)
{
Dictionary<char, string> pairs = new Dictionary<char, string>();
pairs.Add('a', "09001");
...
int index = source.IndexOf(x);
if (index != -1)
{
return source.Remove(index, 1);
}
return source;
}
How can I check if the source string contains one of the 26 keys, delete this key and add the corresponding string to the end of the source-string?
Note: the letter is not always at the end of the source.
Kind regards

Try this:
Dictionary<char, string> pairs = new Dictionary<char, string>();
pairs.Add('a', "09001");
...
foreach(KeyValuePair<string, string> entry in pairs)
{
if (source.Contains(entry.Key)) // .Key must be capitalized
{
source = source.Replace(entry.Key, "") + entry.Value;
break;
}
}
return source;
....

So this is the solution where you have only one letter within your string. You need to find the letter that is within the string, if it exists, and find its index. Then you have to insert the respective value instead of the letter, obtained from the dictionary.
String mystring = "1453400e0000875";
Dictionary<char, string> pairs = new Dictionary<char, string>();
pairs.Add('a', "09001");
pairs.Add('b', "09002");
pairs.Add('c', "09003");
pairs.Add('d', "09004");
pairs.Add('e', "09005");
//...
char letter = mystring.FirstOrDefault(a => Char.IsLetter(a));
if (letter != '\0')
{
int index = mystring.IndexOf(letter);
string substitute;
pairs.TryGetValue(mystring[index], out substitute);
mystring = mystring.Substring(0, index) + substitute + mystring.Substring(index + 1);
}
EDIT:
Using Replace method of the string, the if part can be altered like this:
char letter = mystring.FirstOrDefault(a => Char.IsLetter(a));
if (letter != '\0')
{
string substitute;
pairs.TryGetValue(letter, out substitute);
mystring = mystring.Replace(letter.ToString(), substitute);
}
EDIT2:And if I didn't understand the OP correctly so that he wants to remove the letter and add the replacement string to the end of the source string, the if statement should be like this:
if (letter != '\0')
{
string substitute;
pairs.TryGetValue(letter, out substitute);
mystring = mystring.Replace(letter.ToString(), "");
mystring += substitute;
}
and this is the generalisation when you have more letters within the string. It is the similar solution but requires to iterate over all the letters within the string.
String mystring = "1453a400e0000b875";
Dictionary<char, string> pairs = new Dictionary<char, string>();
pairs.Add('a', "09001");
pairs.Add('b', "09002");
pairs.Add('c', "09003");
pairs.Add('d', "09004");
pairs.Add('e', "09005");
//...
var lettersList = mystring.Where(a => Char.IsLetter(a));
foreach (char letter in lettersList)
{
int index = mystring.IndexOf(letter);
string substitute;
pairs.TryGetValue(mystring[index], out substitute);
mystring = mystring.Substring(0, index) + substitute + mystring.Substring(index + 1);
}
Checked and it works!

Nikola's answer is good and if you like it you should mark it as the answer. However I like this simple method (slightly borrowed a few things :p).
var Alphabet = "abcdefghijklmnopqrstuvwxyz".ToArray();
var Pairs = new Dictionary<char, string>();
for(var i = 1; i < Alphabet.Count() +1; i++)
Pairs.Add(Alphabet[i-1], "090" + (i < 10 ? "0" + i.ToString() : i.ToString()));
var Source = "14534000000875e";
var Chars = Source.Where(x => Char.IsLetter(x));
var Output = string.Empty();
foreach(var Char in Chars)
Output = Source.Replace(Char.ToString(), Pairs[Char]);
or if you want the replacement at the end and only once for repeated chars?
foreach(var Char in Chars)
Output = Source.Replace(Char.ToString(),"") + (Pairs[Char]);

Related

RegularExpressions with C#

How can I use Regular Expressions to split this string
String s = "[TEST name1=\"smith ben\" name2=\"Test\" abcd=\"Test=\" mmmm=\"Test=\"]";
into a list like below:
name1 smith ben
name2 Test
abcd Test=
mmmm Test=`
It is similar to getting attributes from an element but not quite.
The first thing to do is remove the brackets and 'TEST' part from the string so you are just left with the keys and values. Then you can split it (based on '\"') into an array, where the odd entries will be the keys, and the even entries will be the values. After that, it's easy enough to populate your list:
String s = "[TEST name1=\"smith ben\" name2=\"Test\" abcd=\"Test=\" mmmm=\"Test=\"]";
SortedList<string, string> list = new SortedList<string, string>();
//Remove the start and end tags
s = s.Remove(0, s.IndexOf(' '));
s = s.Remove(s.LastIndexOf('\"') + 1);
//Split the string
string[] pairs = s.Split(new char[] { '\"' }, StringSplitOptions.None);
//Add each pair to the list
for (int i = 0; i+1 < pairs.Length; i += 2)
{
string left = pairs[i].TrimEnd('=', ' ');
string right = pairs[i+1].Trim('\"');
list.Add(left, right);
}

Removing matching characters between two strings

I want to remove the characters which are matching between the two given strings. Eg.
string str1 = "Abbbccd";
string str2 = "Ebbd";
From these two strings I want the output as:
"Abcc", only those many matching characters should be removed from str1,which are present in str2.
I tried the following code:
public string Sub(string str1, string str2)
{
char[] arr1 = str1.ToCharArray();
char[] arr2 = str2.ToCharArray();
char[] arrDifference = arr1.Except(arr2).ToArray();
string final = new string(arrDifference);
return final;
}
With this code I get the output as "Ac". It removes all the matching characters between two arrays and stores 'c' only once.
First create this helper method:
IEnumerable<Tuple<char, int>> IndexDistinct(IEnumerable<char> source)
{
var D = new Dictionary<char, int>();
foreach (var c in source)
{
D[c] = D.ContainsKey(c) ? (D[c] + 1) : 0;
yield return Tuple.Create(c, D[c]);
}
}
It converts a string "aabcccd" to [(a,0),(a,1),(b,0),(c,0),(c,1),(c,2),(d,0)]. The idea is to make every character distinct by adding a counting index on equal characters.
Then modify your proposed function like this:
string Sub(string str1, string str2)
{
return new string(
IndexDistinct(str1)
.Except(IndexDistinct(str2))
.Select(x => x.Item1)
.ToArray());
}
Now that you are doing Except on Tuple<char, int> instead of just char, you should get the behavior you specified.
You can do it with lists as well:
List<char> one = new List<char>("Abbbccd".ToCharArray());
List<char> two = new List<char>("Ebbd".ToCharArray());
foreach (char c in two) {
try { one.RemoveAt(one.IndexOf(c)); } catch { }
}
string result = new string(one.ToArray());
Use C#'s string commands to modify the string.
public string testmethod(string str1, string str2)
{
string result = str1;
foreach (char character in str2.ToCharArray())
{
result = result.Replace(character.ToString(), "");
}
return result;
}

C# Reading particular values in a string

I have the following line from a string:
colors numResults="100" totalResults="6806926"
I want to extract the value 6806926 from the above string
How is it possible?
So far, I have used StringReader to read the entire string line by line.
Then what should I do?
I'm sure there's also a regex, but this string approach should work also:
string xmlLine = "[<colors numResults=\"100\" totalResults=\"6806926\">]";
string pattern = "totalResults=\"";
int startIndex = xmlLine.IndexOf(pattern);
if(startIndex >= 0)
{
startIndex += pattern.Length;
int endIndex = xmlLine.IndexOf("\"", startIndex);
if(endIndex >= 0)
{
string token = xmlLine.Substring(startIndex,endIndex - startIndex);
// if you want to calculate with it
int totalResults = int.Parse( token );
}
}
Demo
Consider the this is in Mytext of string type variable
now
Mytext.Substring(Mytext.indexof("totalResults="),7);
//the function indexof will return the point wheres the value start,
//and 7 is a length of charactors that you want to extract
I am using similar of this ........
You can read with Linq2Xml, numResults and totalResults are Attributes, and <colors numResults="100" totalResults="6806926"> is Element, so you can simply get it by nmyXmlElement.Attributes("totalResults").
This function will split the string into a list of key value pairs which you can then pull out whatever you require
static List<KeyValuePair<string, string>> getItems(string s)
{
var retVal = new List<KeyValuePair<String, string>>();
var items = s.Split(' ');
foreach (var item in items.Where(x => x.Contains("=")))
{
retVal.Add(new KeyValuePair<string, string>( item.Split('=')[0], item.Split('=')[1].Replace("\"", "") ));
}
return retVal;
}
You can use regular expressions:
string input = "colors numResults=\"100\" totalResults=\"6806926\"";
string pattern = "totalResults=\"(?<results>\\d+?)\"";
Match result = new Regex(pattern).Match(input);
Console.WriteLine(result.Groups["results"]);
Be sure to have this included:
using System.Text.RegularExpressions;

How to call function over

I have made a function which can replace the position of the chars if they are standing in my list
Code:
public string NoSimilarChar(string password)
{
var listOfSimilarCharacters = new Dictionary<string, string>();
listOfSimilarCharacters.Add("l", "i");
listOfSimilarCharacters.Add("1", "i");
listOfSimilarCharacters.Add("O", "0");
// Iterate through each character
for (int i = 0; i < password.Length; i++)
{
var currentCharacter = password[i].ToString();
// check if the current char exists in either the key or the value of the list of similar characters
if (listOfSimilarCharacters.Keys.Contains(currentCharacter) || listOfSimilarCharacters.Values.Contains(currentCharacter))
{
currentCharacter = currentCharacter.Remove(currentCharacter.Length - 1, 1) + ",";
}
}
return password;
}
Now i want to know how to load the function NoSimilarChar over when the characters is remove
i thought something like this:
if (listOfSimilarCharacters.Keys.Contains(currentCharacter) || listOfSimilarCharacters.Values.Contains(currentCharacter))
{
currentCharacter = currentCharacter.Remove(currentCharacter.Length - 1, 1) + ",";
NoSimilarChar(password);
}
but i think this is not good because he then stays in a loop.
///for replacing
foreach (KeyValuePair<string, string> item in listOfSimilarCharacters)
{
password = password.Replace(item.Key, item.Value);
}
///for removing
foreach (KeyValuePair<string, string> item in listOfSimilarCharacters)
{
if (password.IndexOf(item.Key) >= 0)
password = password.Remove(password.IndexOf(item.Key), 1);
}
try this simpler one
var charsThatCannotbeinUserPwd = new[] {'1', 'l', 'O', '0', 'i'};
// Iterate through each character
var builder = new StringBuilder();
for (int i = 0; i < password.Length; i++)
{
var currentCharacter = password[i];
if (!charsThatCannotbeinUserPwd.Any(x => x.Equals(currentCharacter)))
builder.Append(currentCharacter);
}
return builder.ToString();
It looks like you want to remove a set of characters from you password. If that is the case then you don't need to use a Dictionary. A Dictionary would make more sense if you wanted to replace one character with another. Additionally you do not need to use recursion here. I believe all you need is an array of the characters you want to remove and a simple loop to remove them.
public string NoSimilarChar(string password)
{
string[] charsToRemove = new string[] { "l", "i", "1", "0", "O" }
foreach (string charToRemove in charsToRemove)
{
password = password.Replace(charToRemove, "");
}
return password;
}
FYI: I've defined the array of characters as strings because you will want to replace the character with an empty string and there is no empty character.

How to chop up a string with LINQ

I have a string that needs to be chopped up. I'd like to do this in LINQ.
The string can have up to 32 letters.
I'd like to collect the parts in a dictionary.
The 1st part needs to have the first 4 letters.
The 2nd part needs to have the first 5 letters.
The 3rd part needs to have the first 6 letters.
etc.
The key of the dictionary is simply a counter. I don't know the length of the string, the min. length is 4.
How would I do this createively in LINQ?
I don't know if I understood correctly what you want to do, but maybe you are looking for something like this:
using System;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var s = "This is a simple string";
var dic = Enumerable.Range(4, s.Length-3)
.Select((m, i) => new { Key = i, Value = s.Substring(0, m) })
.ToDictionary(a=>a.Key,a=>a.Value);
}
}
}
You could make it an extension:
public static Dictionary<int, String> Chop(this string str, int minLength)
{
if (str == null) throw new ArgumentException("str");
if (str.Length < minLength) throw new ArgumentException("Length of string less than minLength", "minLength");
var dict = str.TakeWhile((c, index) => index <= str.Length - minLength)
.Select((c, index) => new {
Index = index,
Value = str.Substring(0, minLength + index)
}).ToDictionary(obj => obj.Index, obj => obj.Value);
return dict;
}
Call it in this way:
Dictionary<int, String> = "Insert sample string here".Chop(4);
string word = "abcdefghijklmnopqrstuvwz";
var dict = new Dictionary<int, string>();
for(int i = 0; i < 28;i++)
{
dict[i] = new string(word.Take(i + 4).ToArray());
}

Categories