Insert word before last word in a string - asp.net

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

Related

To remove double quotation in string array

In the below code i have a string array which holds values i want to remove double quotion in the array and display values like 1,2,3,4,5.Pls help me to do this.
DataSet Stock = Chart.ChartCurrentStock(LocationID);
List<string> StockDetails = new List<string>();
foreach (DataRow row in Stock.Tables[0].Rows)
{
StockDetails.Add(row["CurrentStock"].ToString());
}
string[] Stocks = StockDetails.ToArray();
I don't understand your code sample but: ( how it relates?)
If you have a string array and you want one final single string separated with "," :
string[] g = new string[]{"1","2","3"};
var s=string.Join(",",g);
Console.WriteLine (s); // "1,2,3"

Replace more than one character! how?

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.

Custom sort file name string array

I'm retrieving a string array of files and I would like to custom sort them by a substring in the file name...using C# **.NET 3.5. Below is what I am working with.
<% string[] files = System.IO.Directory.GetFiles("...path..." + pageName + "\\reference\\");
files = String.Join(",", files).Replace("...path...", "").Replace("\\reference\\", "").Replace(pageName, "").Split(new Char[] { ',' });
foreach (String item in files)
{
Response.Write("<a href=" + pageName + "/reference/" + System.IO.Path.GetFileName(item) + " target='_blank'>" + item.Replace("_", " ").Replace(".pdf", " ") + "</a>");
}
%>
I'm a C# noob, and I don't know where to go from here. Basically, I'm looking for a substring in the file name to determine the order (e.g., "index","reference","list"; where any file including the string "index" would be listed first). Perhaps there is a better way to do it. Any help would be appreciated.
You can use Linq to order the array by the filenames. In general, use the Path class if you're working with paths.
string fullPath = Path.Combine(directory, pageName, "reference");
var filePaths = Directory.EnumerateFiles(fullPath, "*.*", SearchOption.TopDirectoryOnly)
.Select(fp => new{ FullPath = fp, FileName=Path.GetFileName(fp) })
.OrderByDescending(x => x.FileName.IndexOf("index", StringComparison.OrdinalIgnoreCase) >= 0)
.ThenByDescending(x => x.FileName.IndexOf("reference", StringComparison.OrdinalIgnoreCase) >= 0)
.ThenByDescending(x => x.FileName.IndexOf("list", StringComparison.OrdinalIgnoreCase) >= 0)
.ThenBy(x=> x.FileName)
.Select(x => x.FullPath);
foreach(string filePath in filePaths)
;// ...
If you don't want to compare case-insensitively (so that "index" and "Index" are considered the same) use String.Contains instead of String.IndexOf + StringComparison.OrdinalIgnoreCase.
Here's an easy way I use when I run into this problem.
Define the order of the substrings in a list. Then for each item, check to see whats the first thing that contains that item. Then sort by the order of the substring in the list.
public class SubStringSorter : IComparer<string>
{
public int Compare(string x, string y)
{
var source = x.ToLowerInvariant();
var target = y.ToLowerInvariant();
var types = new List<string> { "base", "data", "model", "services", "interceptor", "controllers", "directives", "filters", "app", "tests", "unittests" };
var sourceType = types.IndexOf(types.FirstOrDefault(source.Contains));
var targetType = types.IndexOf(types.FirstOrDefault(target.Contains));
return sourceType.CompareTo(targetType);
}
}
To sort your files, do something like
var list = new List<string>{ "baseFile", "servicesFile", "this ModElstuff" };
list.Sort(new SubStringSorter());
And the output
You could even go one step further and give the substring sorter the list as part of its constructor so you can re-use the substring sort order with other items. The example I posted tests if the string exists in any context, but if you are more interested in it starting with a string you can do that too.

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