Replace more than one character! how? - asp.net

I am trying to replace more than just the one character that I did without any problem. I'm a newbie so I want to make it really simple if it is possible!
string input = txtmywords.Text.ToString();
string replacements = input.Replace("a","x");
Here i can replace the A with the X. But I want to replace let's say a b c d e f g with x in scentences.

Perhaps this
foreach(Char c in "abcdefg")
input = input.Replace(c, 'x');

You could;
//System.Text.RegularExpressions
string result = Regex.Replace("zzabcdefghijk", "[abcdefg]", "x");
for "zzxxxxxxxhijk"

You can use Regex for doing it.
public class Example
{
public static void Main()
{
string input = "This is text with far too much " +
"whitespace.";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
}
}
Pulling code out from http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx

If you want to replace every letter in a given string with another letter (for ease of use) without manually writing a lot of Replace every time, you could write something like this:
String ReplaceChars(this string input, string chars, string replacement)
{
foreach (var c in chars)
input = input.Replace(c.ToString(), replacement);
return input;
}
Then you could write "abcdefgh".ReplaceChars("acd","x") and this should get you the string xbxxefgh.

Related

How to return String from Optional<String>?

I have the following function.
public String getSomething(){
TextInputDialog dialog = new TextInputDialog();
dialog.setHeaderText("X");
dialog.setTitle("Y");
Optional<String> result = dialog.showAndWait();
return result;
}
Obviously, the returned value is not of String type. How could I return a String when result's type is Optional<String>?
Try doing result.get() should return a string.
I would do something like this to make sure you are protecting from null
if(a. isPresent()) {a.get()}
I'd use orElse which provides a default value in case the actual value is absent:
public String getSomething(){
TextInputDialog dialog = new TextInputDialog();
dialog.setHeaderText("X");
dialog.setTitle("Y");
return dialog.showAndWait().orElse("n/a");
}
Use String.valueOf(optionalString);
Optional<String> s1 =Optional.of("Hello");
// s1 will print - Optional["Hello"]
String s1 = String.valueOf(optionalObj.get());
// now s1 will print "Hello"
this would extract the exact string literal from the optional object.

How to generate a document ID or Report ID of 8 characters in .net

Can someone point me to the preferred method for generating a report or document ID? I have been looking at maybe using a guid that would be reduced down to a shorter length. We have an application that creates an ID for reports that is about 8 characters long. They appear to be using some type of hash code. Probably using a base 36 encoding scheme. But I cant seem to find a way to make the hash code come out to a length of 8 characters since people have to use them to refer to the documents. They would also be used in a disconnected environment, so you couldnt look up the next usable serialized number in the chain. Just wondering what some of you use in applications like this?
The .net Framwork provides RNGCryptoServiceProvider class which Implements a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP). This class is usually used to generate random numbers. Although I can use this class to generate unique number in some sense but it is also not collision less. Moreover while generating key we can make key more complicated by making it as alpha numeric rather than numeric only. So, I used this class along with some character masking to generate unique key of fixed length.
private string GetUniqueKey()
{
int maxSize = 8 ;
int minSize = 5 ;
char[] chars = new char[62];
string a;
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
chars = a.ToCharArray();
int size = maxSize ;
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data) ;
size = maxSize ;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size) ;
foreach(byte b in data )
{ result.Append(chars[__b % (chars.Length - )>); }
<span class="code-keyword">return result.ToString();
}
http://www.codeproject.com/Articles/14403/Generating-Unique-Keys-in-Net
This is what I ended up using. It is a base36 encoding. I borrowed parts of the code from other people, so I cant claim that I wrote it all, but I hope this helps others. This will produce about a 12 digit record ID, or unique ID for databases etc. It uses only the last 2 digits of the year, so it should be good for 100 years.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Base36Converter
{
public partial class Form1 : Form
{
private const string CharList = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public Form1()
{
InitializeComponent();
}
//Base 36 number consists of only numbers and uppercase letters only.
private void button1_Click(object sender, EventArgs e)
{
if (textBox2.Text.Length > 0)
{
label3.Text = "";
//Get Date and Time Stamp
string temp1 = GetTimestamp(DateTime.Now);
//Turn it into a long number
long l = Convert.ToInt64(temp1);
//Now encode it as a base36 number.
string s1 = Encode(l);
//Get userID as a number, i.e. 1055 (User's index number) and create as a long type.
long l1 = Convert.ToInt64(textBox2.Text);
//Encode it as a base36 number.
string s2 = Encode(l1);
//Now display it as the encoded user number + datetime encoded number (Concatenated)
textBox1.Text = s2 + s1;
}
else
{
label3.Text = "User Number must be greater than 0. ie 1055";
}
}
public static String Encode(long input)
{
if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");
char[] clistarr = CharList.ToCharArray();
var result = new Stack<char>();
while (input != 0)
{
result.Push(clistarr[input % 36]);
input /= 36;
}
return new string(result.ToArray());
}
public static String GetTimestamp(DateTime value)
{
return value.ToString("yyMMddHHmmssffff");
}
private void Form1_Load(object sender, EventArgs e)
{
label3.Text = "";
}
}
}

Insert word before last word in a string

I am trying to insert the word "and" before the last word in a string. This is my code so far:
string skillset = "";
foreach (ListItem item in SkillSet.Items)
{
if (item.Selected)
{
skillset += item.Text + ", ";
}
}
skillset = skillset.Substring(0, skillset.Length - 2);
Any help is greatly appreciated.
Thanks
Thomas
If you just want to put "and" in fron of the last word you can use to split your string into an array of strings, change the last word and join the string back together. It would look something like this
string[] skills = skillset.Split(new char[] { ',' });
skills[skills.Length-1] = "and " + skills[skills.Length-1];
skillset = string.Join(",", skills);
This returns a new string in which a specified string is inserted at a specified index position.
Example
string str = "We are loudly";
string mynewvalue = "talking";
str.Insert(str.Length - 1, mynewvalue);
int myStringLength = myString.length;
string myString = inputString.Substring(0, myStringLength);
int index = myString.LastIndexOf(' ');
string outputString = myString.Insert(index , " and ");
Example : http://www.dotnetperls.com/insert

Convert a string to Decimal(10,2)

how can i convert a string to a Decimal(10,2) in C#?
Take a look at Decimal.TryParse, especially if the string is coming from a user.
You'll want to use TryParse if there's any chance the string cannot be converted to a Decimal. TryParse allows you to test if the conversion will work without throwing an Exception.
You got to be careful with that, because some cultures uses dots as a thousands separator and comma as a decimal separator.
My proposition for a secure string to decimal converstion:
public static decimal parseDecimal(string value)
{
value = value.Replace(" ", "");
if (System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ",")
{
value = value.Replace(".", ",");
}
else
{
value = value.Replace(",", ".");
}
string[] splited = value.Split(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]);
if (splited.Length > 2)
{
string r = "";
for (int i = 0; i < splited.Length; i++)
{
if (i == splited.Length - 1)
r += System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
r += splited[i];
}
value = r;
}
return decimal.Parse(value);
}
The loop is in case that string contains both, decimal and thousand separator
Try:
string test = "123";
decimal test2 = Convert.ToDecimal(test);
//decimal test2 = Decimal.Parse(test);
//decimal test2;
// if (decimal.TryParse(test, out result))
//{ //valid }
//else
//{ //Exception }
labelConverted.Text = test2.toString();
Decimal Examples
Difference between Convert.ToDecimal(string) & Decimal.Parse(string)
Regards

Membership Generate Password alphanumeric only password?

How can I use Membership.GeneratePassword to return a password that ONLY contains alpha or numeric characters? The default method will only guarantee a minimum and not a maximum number of non alphanumeric passwords.
string newPassword = Membership.GeneratePassword(15, 0);
newPassword = Regex.Replace(newPassword, #"[^a-zA-Z0-9]", m => "9" );
This regular expression will replace all non alphanumeric characters with the numeric character 9.
I realised that there may be ways of doing this. The GUID method is great, except it doesn't mix UPPER and lower case alphabets. In my case it produced lower-case only.
So I decided to use the Regex to remove the non-alphas then substring the results to the length that I needed.
string newPassword = Membership.GeneratePassword(50, 0);
newPassword = Regex.Replace(newPassword, #"[^a-zA-Z0-9]", m => "");
newPassword = newPassword.Substring(0, 10);
A simple way to get an 8 character alphanumeric password would be to generate a guid and use that as the basis:
string newPwd = Guid.NewGuid().ToString().Substring(0, 8);
If you need a longer password, just skip over the dash using substrings:
string newPwd = Guid.NewGuid().ToString().Substring(0, 11);
newPwd = newPwd.Substring(0, 8) + newPwd.Substring(9, 2); // to skip the dash.
If you want to make sure the first character is alpha, you could just replace it when needed with a fixed string if (newPwd[0] >= '0' && newPwd[0] <= '9')...
I hope someone can find this helpful. :-)
You could also try to generate passwords and concatenate the non alphanumeric characters until you reach the desired password length.
public string GeneratePassword(int length)
{
var sb = new StringBuilder(length);
while (sb.Length < length)
{
var tmp = System.Web.Security.Membership.GeneratePassword(length, 0);
foreach(var c in tmp)
{
if(char.IsLetterOrDigit(c))
{
sb.Append(c);
if (sb.Length == length)
{
break;
}
}
}
}
return sb.ToString();
}
There is similar approach with breigo's solution.
Maybe this is not so effective but so clear and short
string GeneratePassword(int length)
{
var password = "";
while (password.Length < length)
{
password += string.Concat(Membership.GeneratePassword(1, 0).Where(char.IsLetterOrDigit));
}
return password;
}
I also prefer the GUID method - here's the short version:
string password = Guid.NewGuid().ToString("N").Substring(0, 8);
Going from #SollyM's answer, putting a while loop around it, to prevent the very unlikely event of all characters, or too many characters being special characters, and then substring throwing an exception.
private string GetAlphaNumericRandomString(int length)
{
string randomString = "";
while (randomString.Length < length)
{
//generates a random string, of twice the length specified, to counter the
//probability of the while loop having to run a second time
randomString += Membership.GeneratePassword(length * 2, 0);
//replace non alphanumeric characters
randomString = Regex.Replace(randomString, #"[^a-zA-Z0-9]", m => "");
}
return randomString.Substring(0, length);
}
This is what I use:
public class RandomGenerator
{
//Guid.NewGuid().ToString().Replace("-", "");
//System.Web.Security.Membership.GeneratePassword(12, 0);
private static string AllowChars_Numeric = "0123456789";
private static string AllowChars_EasyUpper = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static string AllowChars_EasyLower = "0123456789abcdefghijklmnopqrstuvwxyz";
private static string AllowChars_Upper_Lower = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static string AllowedChars_Difficult = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz##$^*()";
public enum Difficulty
{
NUMERIC = 1,
EASY_LOWER = 2,
EASY_UPPER = 3,
UPPER_LOWER = 4,
DIFFICULT = 5
}
public static string GetRandomString(int length, Difficulty difficulty)
{
Random rng = new Random();
string charBox = AllowedChars_Difficult;
switch (difficulty)
{
case Difficulty.NUMERIC:
charBox = AllowChars_Numeric;
break;
case Difficulty.EASY_LOWER:
charBox = AllowChars_EasyUpper;
break;
case Difficulty.EASY_UPPER:
charBox = AllowChars_EasyLower;
break;
case Difficulty.UPPER_LOWER:
charBox = AllowChars_Upper_Lower;
break;
case Difficulty.DIFFICULT:
default:
charBox = AllowedChars_Difficult;
break;
}
char[] chars = new char[length];
for (int i=0; i< length; i++)
{
chars[i] = charBox[rng.Next(0, charBox.Length)];
}
return new string(chars);
}
}

Resources