String split// manipulation - c#

string keywords = "heard";
string strText = "Have you not heard!! what I said?"
string[] words = strText.Split(' ');
string result = "";
for (int i = 0; i < words.Length; i++)
{
if (words[i].Contains(keywords))
result += "<span>" + words[i] + "</span>" + " ";
else
result += words[i] + " ";
}
I get following output:
Have you not <span>heard!!</span> what I said?
Desired output:
Have you not <span>heard</span>!! what I said?
Can someone guide how can I get the desired output. The strText can only be split with a space.

Use String.Replace
var result = strText.Replace(keywords, "<span>" + keywords + "</span>");
If you have many keywords to replace, then just do replacement in a loop:
string[] keywords = { "heard", "said" };
string result = "Have you not heard!! what I said?";
foreach(var keyword in keywords)
result = result.Replace(keyword, "<span>" + keyword + "</span>");
Alternative solution is regular expression replacement:
string keywords = "heard|said";
string result = "Have you not heard!! what I said?";
result = Regex.Replace(result, keywords, m => "<span>" + m.Value + "</span>");

Why are you even looping through all words? This will give you the same:
string strText = "Have you not heard!! what I said?";
string newText = strText.Replace("heard", "<span>heard</span>");

Related

How to replace variable in user input with math operation?

I need replace variable in string from user. For example:
User input: Ssad asdsdqwdq jdiqwj diqw jd qwld j {price-40%} asd asd asd
I know how replace only {price} but I don't know how to replace other cases.
I need support these cases:
{price}
{price-xx%}
{price+xx%}
{price-xx}
{price+xx}
{price/xx}
{price*xx}
And user can use variable {price} many times.
After user submit text, my app replace variable {price} or calc {price-xx%} and create a new string.
If I understood your problem correctly then I think you can evaluate the whole expression without Replacing variables (might you have to change placements of variables)
First, add 'System.Data' name space in your project
then:
double price = 110;
double xx = 15;
double result = 0;
result = Convert.ToDouble(new DataTable().Compute($"({price-(price*xx)/100})", null));
Console.WriteLine("{price - xx%} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price + (price * xx) / 100})", null));
Console.WriteLine("{price + xx%} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price}-{xx})", null));
Console.WriteLine("{price - xx} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price}+{xx})", null));
Console.WriteLine("{price + xx} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price}/{xx})", null));
Console.WriteLine("{price / xx} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price}*{xx})", null));
Console.WriteLine("{price * xx} = " + result);
https://github.com/davideicardi/DynamicExpresso/
static void Main(string[] args)
{
int price = 100;
Regex regex = new Regex(#"(?<=\{).*?(?=\})");
string userInput = "Hi. I want to buy your computer. I can't offer {price} USD, but I can offer {price-(price/100)*10} USD";
string text = userInput;
foreach (var item in regex.Matches(text))
{
string expression = item.ToString().Replace("price", price.ToString());
var interpreter = new Interpreter();
var result = interpreter.Eval(expression);
text = regex.Replace(text, result.ToString(),1);
text = ReplaceFirst(text, "{", string.Empty);
text = ReplaceFirst(text, "}", string.Empty);
}
Console.WriteLine("Result: " + text);
}
public static string ReplaceFirst(string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}

Ignore case in string split C#

I have a string builder and I want to ignore the case(lower or uppercase) of textbox2.Text when spliting.
Here's the line of code which I think the adjustment must be made.
String[] subStrings = e.Item.Text.Split(new String[] { textBox2.Text }, StringSplitOptions.None);
StringSplitOptions has only two option which is None and RemoveEmptyEntries
My full program would be if I type: "steph" , the text "Steph" in "Stephen" will be highlighted even the textbox2.text first character is lowercase.
My full code:
String[] subStrings = element.Text.Split(new String[] { textBox2.Text }, StringSplitOptions.);
if (subStrings.Count() >= 2)
{
StringBuilder sb = new StringBuilder();
sb.Append(subStrings[0]);
sb.Append("<color=#0193C6>" + textBox2.Text + "</color>");
sb.Append(subStrings[1]);
for (int i = 2; i < subStrings.Count(); i++)
sb.Append(textBox2.Text + subStrings[i]);
element.Text = sb.ToString();
}
Try Using Regex.Split. For e.g.
Regex.Split(textBox2.Text, "pattern", RegexOptions.IgnoreCase);
Try converting both the element and the textbox.Text ToLower().
string elementString = element.Text;
String[] subStrings = elementString.ToLower().Split(new[] { textBox2.Text.ToLower() }, StringSplitOptions.None);
if (subStrings.Count() >= 2)
{
StringBuilder sb = new StringBuilder();
sb.Append(subStrings[0]);
sb.Append("<color=#0193C6>" + textBox2.Text + "</color>");
sb.Append(subStrings[1]);
for (int i = 2; i < subStrings.Count(); i++)
sb.Append(textBox2.Text + subStrings[i]);
element.Text = sb.ToString();
}

String Reverse : reversing only position of the Words in String in c#

original String is "Hello World"
Output Should be "World Hello"
What is the optimized way to do it in c# ?
Please suggest me any existing link if i am missing
var s = "Hello world";
var result = String.Join(" ", s.Split(' ').Reverse()));
OR (better split below if you ar not sure of your data)
var s = "Hello world";
var result = String.Join(" ", Regex.Split(s, #"\s").Reverse());
I would split the sentence by the words (the space between them):
string[] words = helloString.Split(" ");
helloString = words[1] + " " + words[0];
You could optimise this to work with any sentence with any number of words by looping through words from the last element to the first.
I've reassigned the new string back to helloString (the original) as I assume this is what you want based on the question.
Try This Code :
string value = "Hello world";
string firstvalue = value.Split(' ').First();
string secvalue = value.Split(' ').Last();
string value = secvalue + firstvalue;
static void Main(string[] args)
{
String str = "Hello World";
String[] strNames = str.Split(' ');
for(int i=strNames.Length-1;i>=0;i--)
Console.Write(strNames[i]+" ");
}
char[] Delimiter = new char[] { ' ' }
string[] t = string.split("Hello Wordl", Delimiter)
int lenS = t.Count;
string result = "";
for(int x =t-1; t > -1; t--)
{
result += t[x] + " ";
}
//Used result now

From DataGridView to multiline commaSeparated string

I have a DataGridView with four Columns and need to crate a multiline string from its content, separated by comma.
This code works, but probably - there is a more elegant way:
string multiLine = "";
string singleLine;
foreach (DataGridViewRow r in dgvSm.Rows)
{
if (!r.IsNewRow)
{
singleLine = r.Cells[0].Value.ToString() + ","
+ r.Cells[1].Value.ToString() + ","
+ r.Cells[2].Value.ToString() + ","
+ r.Cells[3].Value.ToString() + Environment.NewLine;
multiLine = multiLine + singleLine;
}
}
I don't know about elegant, but:
use StringBuilder for string manipulation, type string is immutable!
if you need to do something in between, separate first or last cycle running (e.g. comma separation)
So, basically something like this:
StringBuilder multiLine = new StringBuilder();
foreach (DataGridViewRow r in dgvSm.Rows)
{
if (!r.IsNewRow)
{
if (r.Cells.Count > 0)
{
multiLine.Append(r.Cells[0].Value.ToString()); //first separated
for (int i = 1; i < r.Cells.Count; ++i)
{
singleLine.Append(','); //between values
singleLine.Append(r.Cells[i].Value.ToString());
}
multiLine.AppendLine();
}
}
}
To illustrate speed difference between StringBuilder concatenation (just dynamic array of characters) and string (new object and copy everything each time you use operator + concatenation), have a look at mini-program:
public static void Main()
{
var sw = new Stopwatch();
sw.Start();
StringBuilder s = new StringBuilder();
//string s = "";
int i;
for (i = 0; sw.ElapsedMilliseconds < 1000; ++i)
//s += i.ToString();
s.Append(i.ToString());
sw.Stop();
Console.WriteLine("using version with type " + s.GetType().Name + " I did " +
i + " times of string concatenation.");
}
For my computer it is:
using version with type String I did 17682 times of string concatenation.
using version with type StringBuilder I did 366367 times of string concatenation.
Try this :
string multiLine = "";
string singleLine;
foreach (DataGridViewRow r in dgvSm.Rows)
{
if (!r.IsNewRow)
{
singleLine = r.Cells[0].Value.ToString() + ","
+ r.Cells[1].Value.ToString() + ","
+ r.Cells[2].Value.ToString() + ","
+ r.Cells[3].Value.ToString() + "\r\n";
multiLine = multiLine + singleLine;
}
}

Variable String.Format length

I have the following code:
var str = "ABC";
var n = 7;
var output = String.Format("{0,n}", str);
This should output the string
" ABC"
How should I change the line above?
Format strings are just strings too - you can define the format separately:
int n = 3;
string format = string.Format("{{0,{0}}}", n);
//or more readable: string format = "{0," + n + "}";
var output = string.Format(format, str);
Edit:
After your update it looks like what you want can also be achieved by PadLeft():
var str = "ABC";
string output = str.PadLeft(7);
Just write:
var lineLength = String.Format("{0," + n + "}", str);
var s="Hello my friend";
string leftSpace = s.PadLeft(20,' '); //pad left with special character
string rightSpace = s.PadRight(20,' '); //pad right with special character

Categories