Split and Join problems - c#

I split them to get first letter to be upper case now I'm having problem merging them and the first letters are still upper cased. Also my data is from a database
private void button1_Click(object sender, EventArgs e)
{
//input = input.Replace("_", "");
string input;
input = table_menu.Text;
string[] words = input.Split('_');
foreach (string word in words)
{
string nword = word.First().ToString().ToUpper() + String.Join("", word.Skip(1));
string merge = String.Join("", nword);
MessageBox.Show(merge);
}
label1.Text = input.First().ToString().ToUpper() + String.Join("", input.Skip(1));
Console.WriteLine(label1.Text);
}
Current Ouput: tablepatient
I want a out to be like this:
TablePatient

The concept of capitalization is culture-specific - capitalization in one culture may not be the same as capitalization in another. If you are serializing your strings to XML for persistent storage, you probably want to use the invariant culture; if you are showing them to a user, then the local culture (or maybe the local UI culture) is appropriate.
That being said, the following probably do the job:
public static string UnderscoreToTitleCase(string input)
{
return UnderscoreToTitleCase(input, System.Globalization.CultureInfo.CurrentCulture);
}
public static string UnderscoreToTitleCaseInvariant(string input)
{
return UnderscoreToTitleCase(input, System.Globalization.CultureInfo.InvariantCulture);
}
public static string UnderscoreToTitleCase(string input, CultureInfo cultureInfo)
{
string[] words = input.Split('_');
StringBuilder sb = new StringBuilder();
foreach (string word in words)
sb.Append(cultureInfo.TextInfo.ToTitleCase(word));
return (sb.ToString());
}

private void button1_Click(object sender, EventArgs e)
{
string input;
input = table_menu.Text;
string[] words = input.Split('_');
StringBuilder sb = new StringBuilder();
foreach (string word in words)
{
string nword = word.First().ToString().ToUpper() + String.Join("", word.Skip(1));
string merge = String.Join("", nword);
MessageBox.Show(merge);
sb.Append(nword);
}
label1.Text = sb.ToString();
Console.WriteLine(label1.Text);
}

This works:
var input = "table_patient";
var output = String.Join("",
input
.Split('_')
.Where(x => !String.IsNullOrEmpty(x))
.Select(x => new string(
x
.Take(1)
.Select(c => char.ToUpperInvariant(c))
.Concat(x.Skip(1))
.ToArray())));
//output == "TablePatient"
This also works:
var output = System
.Globalization
.CultureInfo
.CurrentCulture
.TextInfo
.ToTitleCase(input)
.Replace("_", "");

Related

How can i ignore replace text within specific two symbol

I used following code snippet to replace text
private void textBox1_TextChanged(object sender, EventArgs e)
{
string A = textBox1.Text.Trim();
string B = textBox1.Text.Trim();
A = A.Replace("AB", "CD");
A = A.Replace("GF", "HI");
A = A.Replace("AC", "QW");
A = A.Replace("VB", "GG");
textBox2.Text = (A);
}
but i wants to ignore this replace technique within || these symbol.As a example my code do this
when i type AB GF in a txtbox1,txtbox2 replace as following CD HI.
Now i need when i type |AB GF| in txtbox1 ,txtbox2 replace as AB GF
i used this code to do this
textBox2.Text = ((B.Contains("|")) ? B.Replace("|", "") : A);
but this isn't work,after | this symbol all containing things in txtbox1 not replaced,how can i do this
Per your comments, you will want to split your string on the spaces prior to doing the replacement. Afterwards you will join it all back together. This is pretty easy with Linq.
public Main()
{
var strings = new string[]{ "AB GF", "|AB| GF" };
foreach (var s in strings)
Console.WriteLine(String.Join(" ", s.Split(' ').Select(x => ReplaceText(x))));
}
string ReplaceText(string text)
{
if (text.Contains("|"))
return text.Replace("|", String.Empty);
else
{
text = text.Replace("AB", "CD");
text = text.Replace("GF", "HI");
text = text.Replace("AC", "QW");
return text.Replace("VB", "GG");
}
}
Prints:
CD HI
AB HI
Looking at your code. If you need to avoid a ReplaceText method. Something like this would work.
string A = textBox1.Text.Trim();
var subStrings = A.Split(' ');
for (int i = 0; i < subStrings.Count(); i++)
{
if (subStrings[i].Contains("|"))
subStrings[i] = subStrings[i].Replace("|", String.Empty);
else
{
subStrings[i] = subStrings[i].Replace("AB", "CD");
subStrings[i] = subStrings[i].Replace("GF", "HI");
subStrings[i] = subStrings[i].Replace("AC", "QW");
subStrings[i] = subStrings[i].Replace("VB", "GG");
}
}
textBox2.Text = String.Join(" ", subStrings);

How to sort rich text box in ascending order using c#

I want get out put like 1.2.3.4.5.. but in this code I got values like 1,10,100,101.. plz help me friends
private void btn_load_Click_1(object sender, EventArgs e)
{
{
if (textBox1.Text != "")
{
richTextBox1.Clear();
string tt = #"" + textBox1.Text;
String sdira = #"" + textBox1.Text;
string[] arrays = Directory.GetFiles(sdira, "*", SearchOption.AllDirectories)
.Select(x => Path.GetFileName(x))
.ToArray();// get only file name and extention
foreach (string name in arrays)
{
//StringBuilder sb = new StringBuilder();
richTextBox1.Text += name + "\n";
//i want get out put like 1.2.3.4.5..
//but in this code i got values like 1,10,100,101..
//plz help me friends[first img is my current out put][1]
}
}
}
Sample
If you want sort the strings as numbers instead of lexicographically you have to parse them:
var orderedFiles = Directory.EnumerateFiles(sdira, "*", SearchOption.AllDirectories)
.Select(x => new { file = x, nameNumber = Path.GetFileName(x).TryGetInt32() })
.Where(x => x.nameNumber.HasValue)
.OrderBy(x => x.nameNumber.Value)
.Select(x => x.file); // or x.nameNumber.Value is you want the number
Here's the parse extension method is use in LINQ queries:
public static int? TryGetInt32(this string item, IFormatProvider formatProvider = null, NumberStyles nStyles = NumberStyles.Any)
{
if (formatProvider == null) formatProvider = NumberFormatInfo.CurrentInfo;
int i = 0;
bool success = int.TryParse(item, nStyles, formatProvider, out i);
if (success)
return i;
else
return null;
}

How to remove " [ ] \ from string

I have a string
"[\"1,1\",\"2,2\"]"
and I want to turn this string onto this
1,1,2,2
I am using Replace function for that like
obj.str.Replace("[","").Replace("]","").Replace("\\","");
But it does not return the expected result.
Please help.
You haven't removed the double quotes. Use the following:
obj.str = obj.str.Replace("[","").Replace("]","").Replace("\\","").Replace("\"", "");
Here is an optimized approach in case the string or the list of exclude-characters is long:
public static class StringExtensions
{
public static String RemoveAll(this string input, params Char[] charactersToRemove)
{
if(string.IsNullOrEmpty(input) || (charactersToRemove==null || charactersToRemove.Length==0))
return input;
var exclude = new HashSet<Char>(charactersToRemove); // removes duplicates and has constant lookup time
var sb = new StringBuilder(input.Length);
foreach (Char c in input)
{
if (!exclude.Contains(c))
sb.Append(c);
}
return sb.ToString();
}
}
Use it in this way:
str = str.RemoveAll('"', '[', ']', '\\');
// or use a string as "remove-array":
string removeChars = "\"{[]\\";
str = str.RemoveAll(removeChars.ToCharArray());
You should do following:
obj.str = obj.str.Replace("[","").Replace("]","").Replace("\"","");
string.Replace method does not replace string content in place. This means that if you have
string test = "12345" and do
test.Replace("2", "1");
test string will still be "12345". Replace doesn't change string itself, but creates new string with replaced content. So you need to assign this new string to a new or same variable
changedTest = test.Replace("2", "1");
Now, changedTest will containt "11345".
Another note on your code is that you don't actually have \ character in your string. It's only displayed in order to escape quote character. If you want to know more about this, please read MSDN article on string literals.
how about
var exclusions = new HashSet<char>(new[] { '"', '[', ']', '\\' });
return new string(obj.str.Where(c => !exclusions.Contains(c)).ToArray());
To do it all in one sweep.
As Tim Schmelter writes, if you wanted to do it often, especially with large exclusion sets over long strings, you could make an extension like this.
public static string Strip(
this string source,
params char[] exclusions)
{
if (!exclusions.Any())
{
return source;
}
var mask = new HashSet<char>(exclusions);
var result = new StringBuilder(source.Length);
foreach (var c in source.Where(c => !mask.Contains(c)))
{
result.Append(c);
}
return result.ToString();
}
so you could do,
var result = "[\"1,1\",\"2,2\"]".Strip('"', '[', ']', '\\');
Capture the numbers only with this regular expression [0-9]+ and then concatenate the matches:
var input = "[\"1,1\",\"2,2\"]";
var regex = new Regex("[0-9]+");
var matches = regex.Matches(input).Cast<Match>().Select(m => m.Value);
var result = string.Join(",", matches);

Need to compare values produced from separate foreach loops

I have two foreach loops, each of which loops through a text file, and gets the value of all of the values of the first two columns only (there are more than two columns in the text file, delimited by "|") and puts it in a string. I would like to compare the result of these foreach loops (the values that are output by the Response.Write statements) to see if the strings are equivalent or not. Any thoughts/suggestions appreciated.
protected void Page_Load(object sender, EventArgs e)
{
string textFile1 = #"C:\Test\Test1.txt";
string textFile2 = #"C:\Test\Test2.txt";
string[] textFile1Lines = System.IO.File.ReadAllLines(textFile1);
string[] textFile2Lines = System.IO.File.ReadAllLines(textFile2);
char[] delimiterChars = { '|' };
foreach (string line in textFile1Lines)
{
string[] words = line.Split(delimiterChars);
string column1And2 = words[0] + words[1];
Response.Write(column1And2);
}
foreach (string line in textFile2Lines)
{
string[] words = line.Split(delimiterChars);
string column1And2 = words[0] + words[1];
Response.Write(column1And2);
}
}
One way to compare the outputs would be storing the strings as you go, and then compare the results using SequenceEqual. Since the two loops are identical, consider making a static method out of them:
// Make the extraction its own method
private static IEnumerable<string> ExtractFirstTwoColumns(string fileName) {
return System.IO.File.ReadLines(fileName).Select(
line => {
string[] words = line.Split(delimiterChars);
return words[0] + words[1];
}
);
}
protected void Page_Load(object sender, EventArgs e)
// Use extraction to do both comparisons and to write
var extracted1 = ExtractFirstTwoColumns(#"C:\Test\Test1.txt").ToList();
var extracted2 = ExtractFirstTwoColumns(#"C:\Test\Test2.txt").ToList();
// Write the content to the response
foreach (var s in extracted1) {
Response.Write(s);
}
foreach (var s in extracted2) {
Response.Write(s);
}
// Do the comparison
if (extracted1.SequenceEqual(extracted2)) {
Console.Error.WriteLine("First two columns are different.");
}
}
I would simply compare in the same loop, using for instead of foreach:
protected void Page_Load(object sender, EventArgs e)
{
string textFile1 = #"C:\Test\Test1.txt";
string textFile2 = #"C:\Test\Test2.txt";
string[] textFile1Lines = System.IO.File.ReadAllLines(textFile1);
string[] textFile2Lines = System.IO.File.ReadAllLines(textFile2);
char[] delimiterChars = { '|' };
if (textFile1Lines.Count != textFile2Lines.Count)
{
// Do something since the line counts don't match
}
else
{
foreach (int i = 0; i < textFile1Lines.Count; i++)
{
string[] words1 = textFile1Lines[i].Split(delimiterChars);
string compareValue1 = words1[0] + words1[1];
string[] words2 = textFile2Lines[i].Split(delimiterChars);
string compareValue2 = words2[0] + words2[1];
if (!string.Equals(compareValue1, compareValue2))
{
// Do something
break; // Exit the loop since you found a difference
}
}
}
}

Filtering comma separated String in C#

I have a dynamic String value which may contain values like this
"Apple ,Banana, , , , Mango ,Strawberry , "
I would like to filter this string like
"Apple,Banana,Mango,Strawberry".
I have tried with the following code and it works.
Is there any better approach to achieve the same in C#(.NET 2.0)?
/// <summary>
/// Convert "Comma Separated String" to "Comma Separated String"
/// </summary>
/// <param name="strWithComma">String having values separated by comma</param>
/// <returns>String separated with comma</returns>
private String CommaSeparatedString(String strWithComma)
{
String rtn = String.Empty;
List<String> newList= new List<string>();
if (String.IsNullOrEmpty(strWithComma))
{
return rtn;
}
String[] strArray = strWithComma.Split(",".ToCharArray());
if (strArray == null || strArray.Length == 0)
{
return rtn;
}
String tmpStr = String.Empty;
String separator=String.Empty;
foreach (String s in strArray)
{
if (!String.IsNullOrEmpty(s))
{
tmpStr =s.Replace(Environment.NewLine, String.Empty);
tmpStr = tmpStr.Trim();
if (!String.IsNullOrEmpty(tmpStr))
{
newList.Add(tmpStr);
}
}
}
if (newList != null && newList.Count > 0)
{
rtn = String.Join(",", newList.ToArray());
}
return rtn;
}
you can also use Regex:
string str = #"Apple ,,Banana, , , , Mango ,Strawberry , ";
string result = Regex.Replace(str, #"(\s*,\s*)+", ",").TrimEnd(',');
I believe the following should do the trick on any .NET version:
string[] TrimAll( string[] input )
{
var result = new List<string>();
foreach( var s in input )
result.Add( s.Trim() );
}
return result.ToArray();
}
var delimiters = new [] { ",", "\t", Environment.NewLine };
string result = string.Join(",", TrimAll( input.Split( delimiters, StringSplitOptions.RemoveEmptyEntries ) ) );
Edit: updated to deal with white-space, tabs and newline.
Assuming that your items do not contain spaces:
private String CommaSeparatedString(String strWithComma)
{
string[] tokens = strWithComma
.Replace(" ", "")
.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
return string.Join(",", tokens);
}
Now I'm not sure if C# 2.0 accepts the new char[] {','} syntax. If not, you can define the array somewhere else (as a class private member, for example).
Here's a one-liner:
var outputString = string.Join(",", inputString.Replace(" ", string.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
Regex regex = new Regex(#"\w(?:(?!,| ).)*");
var items = regex.Matches("Apple ,Banana, , , , Mango ,Strawberry , ").Cast<Match>().Select(m => m.Value);
.NET 2.0 Version
List<string> newList = new List<string>();
Regex regex = new Regex(#"\w(?:(?!,| ).)*");
string str = "Apple ,Banana, , , , Mango ,Strawberry , ";
MatchCollection matches = regex.Matches(str);
foreach (Match match in matches)
{
newList.Add(match.Value);
}
var result = Regex.Replace(strWithComma, ",+", ",").TimEnd(',');
result = Regex.Replace(result, "\s+", string.Empty);
With no regular expressions, no splits and joins, trims, etc, O(n) time. StringBuilder is a very good class to work with strings.
EDIT
If the string it doesn't end with a letter it will add a comma. So an extra TrimEnd(',') is added
string strWithComma = ",Apple ,Banana, , , , Mango ,Strawberry , \n John,";
var sb = new StringBuilder();
var addComma = false;
foreach (var c in strWithComma )
{
if (Char.IsLetter(c)) // you might want to allow the dash also: example Anne-Marie
{
addComma = true;
sb.Append(c);
}
else
{
if (addComma)
{
addComma = false;
sb.Append(',');
}
}
}
string rtn = sb.ToString().TrimEnd(',');
Warning this method will only apply for C# 3.0 or higher. Sorry guys didnt read the question well enough
This will work but it can be done much easier like:
string input = "apple,banana,, \n,test\n, ,juice";
var parts = from part in input.Split(',')
let trimmedPart = part.Replace("\n", "")
where !string.IsNullOrWhiteSpace(trimmedPart)
select trimmedPart;
string result = string.Join(",", parts);

Categories

Resources