Multi string replace - c#

im trying to replace normal text with ascii text in this program:
so a will be replaced by â & ETC.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TextConverter
{
public partial class TextCoverter : Form
{
public TextCoverter()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] normal = { "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[] ascii = { "â", "ß", "ç", "ð", "è", "ƒ", "ģ", "н", "ι", "j", "ќ", "ļ", "м", "и", "ю", "ρ", "Ω", "ѓ", "$", "τ", "ט", "Λ", "ш", "χ", "У", "ź" };
for (int i = 0; i < 26; i++)
{
textBox2.Text = textBox1.Text.Replace(normal[i], ascii[i]);
}
}
}
}
But it doesn't replace with Ascii. Please help.

Since you are writing the result into a variable that is different from the original, only the last letter gets replaced. You should either write to the same box, or write to a temp string, and write it to the second box at the end.
var tmp = textBox1.Text;
for (int i = 0; i < 26; i++)
{
tmp = tmp.Replace(normal[i], ascii[i]);
}
textBox2.Text = tmp;
Generally speaking, this is not the most efficient algorithm to do replacements, because it operates on an immutable string. You would be better off creating a mutable string builder, and writing it one character at a time.
const string repl = "âßçðèƒģнιjќļмиюρΩѓ$τטΛшχУź";
var res = new StringBuilder();
foreach (char c in textBox1.Text) {
if (c >= 'a' && c <= 'z') {
res.Append(repl[c-'a']);
} else {
res.Append(c);
}
}
textBox2.Text = res.ToString();

textBox2.Text = textBox1.Text.Replace(normal[i], ascii[i]);
you replace textBox1 again and again, but not save previos state, so work only last loop iteration

Related

Visual Studio C# view output

Working through a string deduplicating and finding that when I rebuild and run the console closes and I don't see what the string is.
using System;
using System.Collections.Generic;
using System.Linq;
namespace StringPrintDuplicates
{
class Program
{
public static void DedupString(List<string> duplicatesString)
{
List<string> distinctList = duplicatesString.Distinct().ToList();
foreach(string deduped in distinctList) {
Console.WriteLine("{0}",deduped);
}
}
static void Main()
{
List<string> list = new List<string>();
list.Add("t");
list.Add("a");
list.Add("l");
list.Add("k");
list.Add("j");
list.Add("l");
list.Add("l");
list.Add("k");
list.Add("k");
list.Add("s");
list.Add("s");
list.Add("h");
list.Add("h");
list.Add("o");
list.Add("e");
Console.WriteLine("The input is: {0} ", list.ToString());
DedupString(list);
}
}
}
When I run this I don't get an errors and the output should be the letters that are duplicated in the list. I am using 2019 and configured to stop console when debugging and also not use "Just my code" but I see nothing. This should return "lksh".
StyleZ and Chandru are correct - . As an aside, as of C#3, you can initialize your lists like this:
var list = new List<string>() { "t", "a", "l", "k", "j", "l", "l", "k", "k", "s", "s", "h", "h", "o", "e" };
This may be easier to write and read.
There are multiple problems I see right after I noticed the code.
Distinct() is a keyword to remove all duplicates
Your list.ToString() will definitely not work, the reason why is that you want to concat all strings together. For this, you should use Aggregate().
If you really want to return just those, that are duplicates, you want to do something like this:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
public static void DedupString(List<string> duplicatesString)
{
List<string> distinctList = duplicatesString.Distinct().ToList();
foreach(string deduped in distinctList) {
Console.Write("{0}",deduped);
}
Console.WriteLine("");
}
public static void DuplicitsOnly(List<string> duplicatesString)
{
var distinctList = duplicatesString.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key).ToList();
foreach(string deduped in distinctList) {
Console.Write("{0}",deduped);
}
Console.WriteLine("");
}
static void Main()
{
List<string> list = new List<string>();
list.Add("t");
list.Add("a");
list.Add("l");
list.Add("k");
list.Add("j");
list.Add("l");
list.Add("l");
list.Add("k");
list.Add("k");
list.Add("s");
list.Add("s");
list.Add("h");
list.Add("h");
list.Add("o");
list.Add("e");
Console.WriteLine("The input is: {0} ", list.Aggregate("", (x, y) => x + y));
DedupString(list);
DuplicitsOnly(list);
}
}
}
Also, about the Console closing ... I had a same problem ... at the right down corner, you should see "Application Output"... I dont know how to fix it for sure, but this was the way I found the console :) ( or just smash a ReadLine(); at the en of a file ... that one should work too )
Alternative way (maybe simpler)
1) You can modify DedupString method like below for showing only duplicate entries:
public static void DedupString(List<string> duplicatesString)
{
List<string> distinctList = duplicatesString.Distinct().ToList();
foreach (string deduped in distinctList)
{
if(duplicatesString.FindAll(x => x.Equals(deduped)).Count > 1)
{
Console.WriteLine("{0}", deduped);
}
}
}
2) Add Console.ReadLine(); at the end of Main() to prevent console from closing. Only after pressing enter key, console will close.

String.Replace does not replace Unicode Character 'ARABIC LETTERS' [duplicate]

This question already has answers here:
string.Replace (or other string modification) not working
(4 answers)
Closed 5 years ago.
I have two arrays, one that contains a set of characters to search for in a specific string and the other the set of strings with which to replace a specific character if found.
I'm trying to use the standard String.Replace() to modify the given string when the specific character is found. The method I'm trying to use detects that the string contains the character/characters of my array, enters the loop and runs the operation but at the end nothing is changed.
I'm not sure why or how to go to solve this. Below is my code and results.
static void Main(string[] args)
{
var wordToPass = "heyك";
wordToPass = wordToPass.MultiReplace();
Console.WriteLine(wordToPass);
Console.ReadKey();
}
The extension method to replace the characters:
public static class StringExtension
{
public static readonly char[] SignsArray = new char[] { 'ك', 'ـ', 'ض', 'ؤ', 'ا', 'ط', 'ئ', 'إ', 'ر', 'أ', ' ', 'ہ', 'ء', 'ب', 'ة', 'ت', 'ز',
'س', 'ص', 'ظ', 'ع', 'ج', 'ح', '´', 'ف', 'ث', '¶', '°', '؛', '·', '`' };
public static readonly string[] RepArray = new string[] { "SS", "UE", "OE", "AE", "C", "OE", "AE", "AA", "N", "A", "A", "A", "A", "E", "E", "E", "O", "O", "O",
"U", "U", "I", "I", "'", "Y", "E", "A", ".", ".", ".", "'"};
// Extension on String
public static string MultiReplace(this string stringValue)
{
HashSet<char> set = new HashSet<char>(SignsArray);
for (int i = 0; i < stringValue.Length; ++i)
{
var currentCharacter = stringValue[i];
string valueToReplace;
string replaceValue;
if (set.Contains(currentCharacter))
{
valueToReplace = Char.ToString(stringValue[i]);
replaceValue = RepArray[Array.IndexOf(SignsArray, currentCharacter)];
stringValue.Replace(Convert.ToString(currentCharacter), replaceValue);
}
}
return stringValue;
}
}
.Replace returns a new string, as System.String is immutable.
Consider reassigning.
stringValue = stringValue.Replace(Convert.ToString(currentCharacter), replaceValue);

Check if string has some special characters in C# [duplicate]

I want to check if a String s, contains "a" or "b" or "c", in C#.
I am looking for a nicer solution than using
if (s.contains("a")||s.contains("b")||s.contains("c"))
Well, there's always this:
public static bool ContainsAny(this string haystack, params string[] needles)
{
foreach (string needle in needles)
{
if (haystack.Contains(needle))
return true;
}
return false;
}
Usage:
bool anyLuck = s.ContainsAny("a", "b", "c");
Nothing's going to match the performance of your chain of || comparisons, however.
Here's a LINQ solution which is virtually the same but more scalable:
new[] { "a", "b", "c" }.Any(c => s.Contains(c))
var values = new [] {"abc", "def", "ghj"};
var str = "abcedasdkljre";
values.Any(str.Contains);
If you are looking for single characters, you can use String.IndexOfAny().
If you want arbitrary strings, then I'm not aware of a .NET method to achieve that "directly", although a regular expression would work.
You can try with regular expression
string s;
Regex r = new Regex ("a|b|c");
bool containsAny = r.IsMatch (s);
If you need ContainsAny with a specific StringComparison (for example to ignore case) then you can use this String Extentions method.
public static class StringExtensions
{
public static bool ContainsAny(this string input, IEnumerable<string> containsKeywords, StringComparison comparisonType)
{
return containsKeywords.Any(keyword => input.IndexOf(keyword, comparisonType) >= 0);
}
}
Usage with StringComparison.CurrentCultureIgnoreCase:
var input = "My STRING contains Many Substrings";
var substrings = new[] {"string", "many substrings", "not containing this string" };
input.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// The statement above returns true.
”xyz”.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// This statement returns false.
This is a "nicer solution" and quite simple
if(new string[] { "A", "B", ... }.Any(s=>myString.Contains(s)))
List<string> includedWords = new List<string>() { "a", "b", "c" };
bool string_contains_words = includedWords.Exists(o => s.Contains(o));
public static bool ContainsAny(this string haystack, IEnumerable<string> needles)
{
return needles.Any(haystack.Contains);
}
As a string is a collection of characters, you can use LINQ extension methods on them:
if (s.Any(c => c == 'a' || c == 'b' || c == 'c')) ...
This will scan the string once and stop at the first occurance, instead of scanning the string once for each character until a match is found.
This can also be used for any expression you like, for example checking for a range of characters:
if (s.Any(c => c >= 'a' && c <= 'c')) ...
// Nice method's name, #Dan Tao
public static bool ContainsAny(this string value, params string[] params)
{
return params.Any(p => value.Compare(p) > 0);
// or
return params.Any(p => value.Contains(p));
}
Any for any, All for every
static void Main(string[] args)
{
string illegalCharacters = "!##$%^&*()\\/{}|<>,.~`?"; //We'll call these the bad guys
string goodUserName = "John Wesson"; //This is a good guy. We know it. We can see it!
//But what if we want the program to make sure?
string badUserName = "*_Wesson*_John!?"; //We can see this has one of the bad guys. Underscores not restricted.
Console.WriteLine("goodUserName " + goodUserName +
(!HasWantedCharacters(goodUserName, illegalCharacters) ?
" contains no illegal characters and is valid" : //This line is the expected result
" contains one or more illegal characters and is invalid"));
string captured = "";
Console.WriteLine("badUserName " + badUserName +
(!HasWantedCharacters(badUserName, illegalCharacters, out captured) ?
" contains no illegal characters and is valid" :
//We can expect this line to print and show us the bad ones
" is invalid and contains the following illegal characters: " + captured));
}
//Takes a string to check for the presence of one or more of the wanted characters within a string
//As soon as one of the wanted characters is encountered, return true
//This is useful if a character is required, but NOT if a specific frequency is needed
//ie. you wouldn't use this to validate an email address
//but could use it to make sure a username is only alphanumeric
static bool HasWantedCharacters(string source, string wantedCharacters)
{
foreach(char s in source) //One by one, loop through the characters in source
{
foreach(char c in wantedCharacters) //One by one, loop through the wanted characters
{
if (c == s) //Is the current illegalChar here in the string?
return true;
}
}
return false;
}
//Overloaded version of HasWantedCharacters
//Checks to see if any one of the wantedCharacters is contained within the source string
//string source ~ String to test
//string wantedCharacters ~ string of characters to check for
static bool HasWantedCharacters(string source, string wantedCharacters, out string capturedCharacters)
{
capturedCharacters = ""; //Haven't found any wanted characters yet
foreach(char s in source)
{
foreach(char c in wantedCharacters) //Is the current illegalChar here in the string?
{
if(c == s)
{
if(!capturedCharacters.Contains(c.ToString()))
capturedCharacters += c.ToString(); //Send these characters to whoever's asking
}
}
}
if (capturedCharacters.Length > 0)
return true;
else
return false;
}
You could have a class for your extension methods and add this one:
public static bool Contains<T>(this string s, List<T> list)
{
foreach (char c in s)
{
foreach (T value in list)
{
if (c == Convert.ToChar(value))
return true;
}
}
return false;
}
You can use Regular Expressions
if(System.Text.RegularExpressions.IsMatch("a|b|c"))
If this is for a password checker with requirements, try this:
public static bool PasswordChecker(string input)
{
// determins if a password is save enough
if (input.Length < 8)
return false;
if (!new string[] { "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", "Ä", "Ü", "Ö"}.Any(s => input.Contains(s)))
return false;
if (!new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}.Any(s => input.Contains(s)))
return false;
if (!new string[] { "!", "'", "§", "$", "%", "&", "/", "(", ")", "=", "?", "*", "#", "+", "-", "_", ".",
",", ";", ":", "`", "´", "^", "°", }.Any(s => input.Contains(s)))
return false;
return true;
}
This will set a password to have a min length of 8, have it use at least one uppercase char, at least one number, and at least one of the special chars

How do I count vowels in a string C# [duplicate]

This question already has answers here:
C# Count Vowels
(20 answers)
Closed 8 years ago.
I am working on a program that is designed to count the vowels in a word, however I am having trouble counting the vowels per word. My current code looks like this:
string word;
string[] ca = { "a", "e", "i", "o", "u", "A", "E", "I", "O", "U" };
int va = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (ca.Contains(word))
{
label1.Text = "Vowel Count: " + va;
}
else
{
label1.Text = "Vowel Count: " + va;
}
}
Thanks for the help!
The easiest way is to split the string into words to start with. This can be achieved with the help of the string Split() method:
// you need to decide what the word separators are:
var words = text.Split(new char[]{'.', ',', ':', ';', '\r', '\t', '\n'});
Once done it's just a for loop:
foreach (var word in words)
{
foreach (var character in word)
{
if (vowels.Any(x => x == character))
++count;
}
}
You could do it like:
string word = "myword";
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
int vowelCount = word.Count(x => vowels.Contains(Char.ToLower(x)));

Adding the same items to multiple comboboxes

I have 30 comboboxes and in each one of them I have to add the same items. Is there a faster way to do this than typing the same code all over again for 30 times?
comboBox1.Items.Add("K");
comboBox1.Items.Add("H");
comboBox1.Items.Add("L");
comboBox1.Items.Add("T");
comboBox1.SelectedIndex = 0;
comboBox2.Items.Add("K");
comboBox2.Items.Add("H");
comboBox2.Items.Add("L");
comboBox2.Items.Add("T");
comboBox2.SelectedIndex = 1;
... and so on..
string[] values = new[] { "K", "H", "L", "T" };
foreach(string value in values)
{
combobox1.Items.Add(value);
combobox2.Items.Add(value);
}
Even better, if the ItemsCollection has an AddRange method:
string[] values = new[] { "K", "H", "L", "T" };
combobox1.Items.AddRange(values);
combobox2.Items.AddRange(values);
You can iterate over all comboboxes using OfType method:
int i = 0;
foreach(var cmbBox in this.Controls.OfType<ComboBox>())
{
cmbBox.Items.Add("K");
cmbBox.Items.Add("H");
cmbBox.Items.Add("L");
cmbBox.Items.Add("T");
cmbBox.SelectedIndex = i++;
}
InitComboBox(comboBox1);
InitComboBox(comboBox2);
...
private void InitComboBox(ComboBox cb)
{
cb.Items.Add("K");
cb.Items.Add("H");
cb.Items.Add("L");
cb.Items.Add("T");
cb.SelectedIndex = 0;
}
You add a method FillCombo
void FillCombo(Control ctrl)
{
foreach (ComboBox cb in ctrl.Controls)
{
cb.Items.Add("K");
cb.Items.Add("H");
cb.Items.Add("L");
cb.Items.Add("T");
cb.SelectedIndex = 0;
}
}
To use it :
FillCombo(this);

Categories