how do I replace numbers using regex? - c#

I am using C# regex library to do some text find and replace.
I would like to change the following:
1 -> one
11 -> one one
123 -> one two three
for example, here's my code to replace ampersand:
string pattern = "[&]";
string replacement = " and ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(text, replacement);
Edit
I found some great examples of .NET RegEx on MSDN:
http://msdn.microsoft.com/en-us/library/kweb790z.aspx

Since you're specifically asking for a regex, you could do something like this
var digits = new Dictionary<string, string> {
{ "0", "zero" },
{ "1", "one" },
{ "2", "two" },
{ "3", "three" },
{ "4", "four" },
{ "5", "five" },
{ "6", "six" },
{ "7", "seven" },
{ "8", "eight" },
{ "9", "nine" }
};
var text = "this is a text with some numbers like 123 and 456";
text = Regex.Replace(text, #"\d", x => digits[x.Value]);
which will give you
this is a text with some numbers like onetwothree and fourfivesix

Related

Splitting String of Numbers into String[]

Splitting a string of numbers separated by spaces or commas into a string array doesn't seem to work.
Using the code
string numStr = "12 13 2 7 8 105 6 5 29 0";
char[] delimiterChars = { ' ', ',' };
string[] numArray = numStr.Split(delimiterChars);
I expect numbers to contain "12", "13", "2", "7", "8", "105", "6", "5", "29", "0" but instead numArray[0] = "12 13 2 7 8 105 6 5 29 0"
I've also tried using the following code but it doesn't work either.
string[] keywords = Regex.Split(numstr, #"(?<=\d) |, ");

Add arrays to a higher dimension array

I am creating an app that gets information and download movies from a site. I have succeeded in setting the information in different arrays and combining them together to 1 array.
However, now I am trying to put that array inside a bigger array (want to work with JSON), and that is failing.
My current Json output looks like this:
{"moviedata":
["http:/xxxx","title title ","k0X0HrYtMm5u"],"tags":
["x","x","x","Prop","x","x","x","x","x","x","x"],"categorydata":
["x","x","x"]}
Which is achieved with this code:
Dictionary<string, string[]> movie = new Dictionary<string, string[]>();
moviedata.Add("moviedata", moviegenerala);
moviedata.Add("tags", tagsa);
moviedata.Add("categorydata", categoriesa);
string moviejson = JsonConvert.SerializeObject(moviedata);
I want to add another layer on top of this, so there is a general tab named "Movie", and for each movie it has this information. How would I do that?
UPDATE:
Added this code:
var myShape = new
{
Movie = new Dictionary<string, string[]>
{
["moviedata"] = moviegenerala,
["tags"] = tagsa,
["categorydata"] = categoriesa,
["localdata"] = localdataa
}
};
var moviejson = JsonConvert.SerializeObject(myShape);
The JSON seems to be correct, but it cannot parse, after the first listing it says there is text after the closing bracket.
UPDATE:
Changed code to this:
Dictionary<string, string[]> movies = new Dictionary<string, string[]>();
var myShape = movies.Select(m => new
{
Movie = new Dictionary<string, string[]>
{
// TODO - you'll need to get the appropriate data for this movie
["moviedata"] = moviegenerala,
["tags"] = tagsa,
["categorydata"] = categoriesa,
["localdata"] = localdataa
}
});
var moviejson = JsonConvert.SerializeObject(myShape);
File.AppendAllText("moviedata.txt", moviejson);
But now it only gives empty brackets :(
If this is a one-off serialization, then simplest could be just to wrap the Dictionary with an anonymous class adding the extra property indentation, e.g.
var myShape = new
{
Movie = new Dictionary<string, string[]>
{
["moviedata"] = moviegenerala,
["tags"] = tagsa,
["categorydata"] = categoriesa
}
};
var moviejson = JsonConvert.SerializeObject(myShape);
However, if this same shape is required in multiple places in your code, then I would recommend that you create a fully fledged class for your 'Shape'.
Edit:
The json produced by the above is
{
"Movie": {
"moviedata": [ "http:/xxxx", "title title ", "k0X0HrYtMm5u" ],
"tags": [ "x", "x", "x", "Prop", "x", "x", "x", "x", "x", "x", "x" ],
"categorydata": [ "x", "x", "x" ]
}
}
If you need to map multiple Movies, then project then you can use a .Select:
// TODO : Replace this with your actual current movies
var inMovies = new[] {new Movie{...},new Movie {...}, ...};
var myShape = inMovies.Select(m => new
{
Movie = new Dictionary<string, string[]>
{
// TODO - you'll need to get the appropriate data for this movie, e.g. m.moviegenerala
["moviedata"] = moviegenerala,
...
}
});
Produces the following:
[
{
"Movie": {
"moviedata": [ "http:/xxxx", "title title ", "k0X0HrYtMm5u" ],
"tags": [ "x", "x", "x", "Prop", "x", "x", "x", "x", "x", "x", "x" ],
"categorydata": [ "x", "x", "x" ]
}
},
{
"Movie": {
"moviedata": [ "http:/xxxx", "title title ", "k0X0HrYtMm5u" ],
"tags": [ "x", "x", "x", "Prop", "x", "x", "x", "x", "x", "x", "x" ],
"categorydata": [ "x", "x", "x" ]
}
}
]

How do I use string.replace() with chars?

So full disclousre this is homework. Anyway trying to make a morse code converter and I am just stuck on this last issue. I want to use chars and then use string.replace but I can't since my dictionary is all strings. I want to use chars though. So how would I get around this?
public void InputReader()
{
string inputForTranslating = inputForTranslator.Text;
Dictionary<string, string> morseDictionary = new Dictionary<string, string>
{
{ " ", " " }, { ",", "--..--" }, { ".", ".-.-.-" }, { "\\?", "..--.." }, { "0", "-----" }, { "1", ".----" }, { "2", "..---" }, { "3", "...--" },
{ "4", "....-" }, { "5", "....." }, { "6", "-...." }, { "7", "--..." }, { "8", "---.." }, { "9", "----." }, { "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[] charArray = inputForTranslating.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
outPutTranslation.Text = outPutTranslation.ToString().Replace(morseDictionary.Keys, morseDictionary.Values); ////This is where the error occurs "cannot convert from 'System.Collections.Generic.Dictionary<string, string>.KeyCollection' to 'char'"
}
}
Replace takes strings/chars as parameters, not a collection of keys or values.
In this case, you don't even need the Replace, you can just add the values based on the keys.
Also, your outPutTranslation.Text will only have the last char.
Dictionary<string, string> morseDictionary = new Dictionary<string, string>
{
{ " ", " " }, { ",", "--..--" }, { ".", ".-.-.-" }, { "\\?", "..--.." }, { "0", "-----" }, { "1", ".----" }, { "2", "..---" }, { "3", "...--" },
{ "4", "....-" }, { "5", "....." }, { "6", "-...." }, { "7", "--..." }, { "8", "---.." }, { "9", "----." }, { "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 output = "";
foreach (char c in inputForTranslating.ToCharArray())
{
output += morseDictionary[c];
}
outPutTranslation.Text = output;
Well, string.Replace() works both with two chars or two strings. The error clearly states that morseDictionary.Keys is not a string. Neither is morseDictionary.Values. And it's right, they are the list of keys and values of the dictionary!
There's another mistake in that code. You're converting your input to a char array, and then iterating each character, and trying to replace there. Think about what it's doing:
If you have -.-, in the first iteration you will search over -, in the second over . and lastly over -. You'll never be able to find the K.
You should iterate your dictionary, and search each word in the whole string.
foreach(string key in morseDictionary) {
//for morse->letter
inputForTranslating=inputForTranslating.Replace(morseDictionary[key],key);
//for letter->morse
inputForTranslating=inputForTranslating.Replace(key,morseDictionary[key]);

Compare two List<string> using LINQ in C#

What is the best way to compare two lists based on values, order and the number of values. So all of the lists below should be different.
var list1 = new List<string> { "1", "2" };
var list2 = new List<string> { "2", "1" };
var list3 = new List<string> { "1", "2", "3" };
How about using SequenceEqual.
See http://ideone.com/yZeYRh
var a = new [] { "1", "2", "3" };
var b = new [] { "1", "2" };
var c = new [] { "2", "1" };
Console.WriteLine(a.SequenceEqual(b)); // false
Console.WriteLine(a.SequenceEqual(c)); // false
Console.WriteLine(c.SequenceEqual(b)); // false
It comes from the namespace System.Linq and can be used on any IEnumerable.
You can also pass it an IEqualityComparer to for example also do:
var d = new [] { "a", "B" };
var e = new [] { "A", "b" };
Console.WriteLine(d.SequenceEqual(e, StringComparer.OrdinalIgnoreCase)); // true
I like Zip for this, but you still need to manually compare Count.
lista.Count() ==listb.Count() && lista.Zip(listb, Equals).All(a=>a);

C# - Number to String Mapping - Tough Logic

My TL asked me to implement this:
If we have the alphabets in english numbered as
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 1
k 2
l 3
m 4
n 5
o 6
p 7
q 8
r 9
s 1
t 2
u 3
v 4
w 5
x 6
y 7
z 8
the vowels would be
a 1
e 5
i 9
o 6
u 3
The User would enter :
Number of Vowels
Sum
Number of Characters
Now I need to display a string of length : number of Characters entered by user.
The String would have two Parts:
The first Part would have the Vowels with sum entered by the user.
The second part would be of length [Number of Chars entered by user - Vowels as per the first half of string above] and the sum would be the same entered by user.
Can any body write C# code for this. I tried real hard but could not figure it out.
Any help would be greatly appreciated.
Here's my code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VowelsAndConsonants
{
class Program
{
static void Main(string[] args)
{
//Gather Info from the User
Console.WriteLine("Please Enter Number of Vowels");
string numVowels = Console.ReadLine();
Console.WriteLine("Please Enter the Total");
string total = Console.ReadLine();
Console.WriteLine("Please Enter the Number of Chars");
string numChars = Console.ReadLine();
//Convert the Strings entered by User to int
int inNumVowels = Convert.ToInt16(numVowels);
int intTotal = Convert.ToInt16(total);
int intNumChars = Convert.ToInt16(numChars);
//Populate the Array with all the alphanets
string[,] arr = new string[,] { { "a", "1" }, { "b", "2" }, { "c", "3" }, { "d", "4" }, { "e", "5" }, { "f", "6" }, { "g", "7" }, { "h", "8" }, { "i", "9" }, { "j", "1" }, { "k", "2" }, { "l", "3" }, { "m", "4" }, { "n", "5" }, { "o", "6" }, { "p", "7" }, { "q", "8" }, { "r", "9" }, { "s", "1" }, { "t", "2" }, { "u", "3" }, { "v", "4" }, { "w", "5" }, { "x", "6" }, { "y", "7" }, { "z", "8" } };
string[] resArr= new string[20];// = null;
for (int i = 0; i < intNumChars; i++)
{
//The logic you guys would suggest goes here
resArr[0]=arr[,];
//Display the string
Console.WriteLine("");
}
}
}
}
The hard part isn't writing the code. The hard part is figuring out what the algorithm is that solves this problem. Once you have the algorithm solid, turning it into code will be straightforward.
What are your thoughts on the algorithm? Start with some contrived examples. For instance, suppose you are given 1/9/2. A solution to that is IR. How would you, as a human, come up with that solution? Can you describe a method whereby you, a human, could always come up with the answer?
I think that you are on the wrong track with using mod.
It seems to me that this is a variation to a "greedy algorithm" problem, normaly associated with working out efficient change with coins in homework questions, but I think this seems to be a variant of it.
Wikipedia has a page on it, and I am sure googling greedy algorithm will help you out.

Categories

Resources