Replace string after at with another string - c#

I have two strings.
First string:
"31882757623"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738
Second string:vandrielfinance.nl
I want to replace asklync.nl to vandrielfinance.nl in the first string after the # with the second string (vandrielfinance.nl). Everything else will stay the same.
So the new string will be:
"31882757623"<sip:+31882757623#vandrielfinance.nl;user=phone>;epid=5440626C04;tag=daa784a738
Here is what I have so far:
static string ReplaceSuffix(string orginal, string newString)
{
string TobeObserved = "#";
orginal = "\"31882757623\"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738";
string second = "vandrielfinance.nl";
string pattern = second.Substring(0, second.LastIndexOf("#") + 1);
string code = orginal.Substring(orginal.IndexOf(TobeObserved) + TobeObserved.Length);
//newString = Regex.Replace(code,second, pattern);
newString = Regex.Replace(second, orginal, pattern);
string hallo = orginal.Replace(newString, second);
Console.Write("Original String: {0}", orginal);
Console.Write("\nReplacement String: \n{0}", newString);
Console.WriteLine("\n" + code);
return newString;
}

why not string.Replace?
string s = "\"31882757623\"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738";
string t = "vandrielfinance.nl";
string u = s.Replace("asklync.nl", t);
Console.WriteLine(u);

I'm not really a fan a string.Split(), but it made for quick work in this case:
static string ReplaceSuffix(string orginal, string newString)
{
var segments = original.Split(";".ToCharArray());
var segments2 = segments[0].Split("#".ToCharArray());
segments2[1] = newString;
segments[0] = string.Join("#", segments2);
var result = string.Join(";", segments);
Console.WriteLine("Original String:\n{0}\nReplacement String:\n{1}, original, result);
return result;
}
If the original domain will really always be asklync.nl, you may even be able to just do this:
static string ReplaceSuffix(string orginal)
{
var oldDomain = "asklync.nl";
var newDomain = "vandrielfinance.nl";
var result = original.Replace(oldDomain, newDomain);
Console.WriteLine("Original String:\n{0}\nReplacement String:\n{1}, original, result);
return result;
}

This should work
var orginal = "\"31882757623\"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738";
string second = "vandrielfinance.nl";
var returnValue = string.Empty;
var split = orginal.Split('#');
if (split.Length > 0)
{
var findFirstSemi = split[1].IndexOf(";");
var restOfString = split[1].Substring(findFirstSemi, split[1].Length - findFirstSemi);
returnValue = split[0] + "#" + second + restOfString;
}
Console.WriteLine("Original String:");
Console.WriteLine("{0}", orginal);
Console.WriteLine("Replacement String:");
Console.WriteLine("{0}", returnValue);
//return returnValue;

I'm not a huge fan of RegEx or string.Split, especially when a string function already exists to replace a portion of a string.
string orginal = "\"31882757623\"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738";
string second = "vandrielfinance.nl";
int start = orginal .IndexOf("#");
int end = orginal .IndexOf(";", start);
string newString = orginal .Replace(orginal.Substring(start, end-start), second );
Console.WriteLine(orginal );
Console.WriteLine(newString);

Related

How Describe all duplicate string or number without remove duplicate in C#

if i input string or number.
Example Input : 02x2, 05x3, 05x3, 02x4, 19.02x21, 21.02x3
I want ouput :
02x2
02x4
05x3
05x3
02x3
02x21
Helpme
Try This
string str = "02x2, 05x3, 05x3, 02x4, 19.02x21, 21.02x3";
var str1 = str.Split(',');
string test = "";
List<string> strs = new List<string>();
foreach (var item in str1.OrderBy(x => x.Trim()))
{
var str2 = item.Split('x');
string i = "";
if (str2[0].ToString().Contains("."))
{
var st = str2[0].ToString().Split('.');
i = st[st.Count() -1];
}
else
{
i = str2[0].ToString();
}
test += i.ToString() + 'x' + str2[1].ToString() + ",";
}
test.TrimEnd(',');
Output : 02x2, 02x4, 05x3, 05x3,02x21,02x3

extract numerical values from string after dash (-)

I have string value like this Rs.100 - Rs.250 Now I want only 250 from this string.
I tried this but it's not getting output
var result = str.Substring(str.LastIndexOf('-') + 1);
UPDATE
string result = price.Text;
string[] final_result = result.Split('.');
dynamic get_result = final_result(1).ToString();
price.Text = final_result.ToString;
Try this code after getting the result of Rs.250.
var data = Regex.Match(result, #"\d+").Value;
Do it like this:
string str = "Rs.100-Rs.250";
var result = str.Substring(str.LastIndexOf('-') + 1);
String[] final_result = result.Split('.');
var get_result = final_result[1].ToString();
this will get 250 as you wanted.
try this
var result = ("Rs.100 - Rs.250").Split('-').LastOrDefault().Split('.').LastOrDefault();

C# convert a string to unicode encoding

I need to convert a string i.e. "hi" to & #104;& #105; is there a simple way of doing this? Here is a website that does what I need. http://unicode-table.com/en/tools/encoder/
Try this:
var s = "hi";
var ss = String.Join("", s.Select(c => "&#" + (int)c + ";"));
Try this:
string myString = "Hi there!";
string encodedString = myString.Aggregate("", (current, c) => current + string.Format("&#{0};", Convert.ToInt32(c)));
Based on the answer to this question:
static string EncodeNonAsciiCharacters(string value)
{
StringBuilder sb = new StringBuilder();
foreach (char c in value)
{
string encodedValue = "&#" + ((int)c).ToString("d4"); // <------- changed
sb.Append(encodedValue);
}
return sb.ToString();
}

Remove words from string c#

I am working on a ASP.NET 4.0 web application, the main goal for it to do is go to the URL in the MyURL variable then read it from top to bottom, search for all lines that start with "description" and only keep those while removing all HTML tags. What I want to do next is remove the "description" text from the results afterwords so I have just my device names left. How would I do this?
protected void parseButton_Click(object sender, EventArgs e)
{
MyURL = deviceCombo.Text;
WebRequest objRequest = HttpWebRequest.Create(MyURL);
objRequest.Credentials = CredentialCache.DefaultCredentials;
using (StreamReader objReader = new StreamReader(objRequest.GetResponse().GetResponseStream()))
{
originalText.Text = objReader.ReadToEnd();
}
//Read all lines of file
String[] crString = { "<BR> " };
String[] aLines = originalText.Text.Split(crString, StringSplitOptions.RemoveEmptyEntries);
String noHtml = String.Empty;
for (int x = 0; x < aLines.Length; x++)
{
if (aLines[x].Contains(filterCombo.SelectedValue))
{
noHtml += (RemoveHTML(aLines[x]) + "\r\n");
}
}
//Print results to textbox
resultsBox.Text = String.Join(Environment.NewLine, noHtml);
}
public static string RemoveHTML(string text)
{
text = text.Replace(" ", " ").Replace("<br>", "\n");
var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>");
return oRegEx.Replace(text, string.Empty);
}
Ok so I figured out how to remove the words through one of my existing functions:
public static string RemoveHTML(string text)
{
text = text.Replace(" ", " ").Replace("<br>", "\n").Replace("description", "").Replace("INFRA:CORE:", "")
.Replace("RESERVED", "")
.Replace(":", "")
.Replace(";", "")
.Replace("-0/3/0", "");
var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>");
return oRegEx.Replace(text, string.Empty);
}
public static void Main(String[] args)
{
string str = "He is driving a red car.";
Console.WriteLine(str.Replace("red", "").Replace(" ", " "));
}
Output:
He is driving a car.
Note: In the second Replace its a double space.
Link : https://i.stack.imgur.com/rbluf.png
Try this.It will remove all occurrence of the word which you want to remove.
Try something like this, using LINQ:
List<string> lines = new List<string>{
"Hello world",
"Description: foo",
"Garbage:baz",
"description purple"};
//now add all your lines from your html doc.
if (aLines[x].Contains(filterCombo.SelectedValue))
{
lines.Add(RemoveHTML(aLines[x]) + "\r\n");
}
var myDescriptions = lines.Where(x=>x.ToLower().BeginsWith("description"))
.Select(x=> x.ToLower().Replace("description",string.Empty)
.Trim());
// you now have "foo" and "purple", and anything else.
You may have to adjust for colons, etc.
void Main()
{
string test = "<html>wowzers description: none <div>description:a1fj391</div></html>";
IEnumerable<string> results = getDescriptions(test);
foreach (string result in results)
{
Console.WriteLine(result);
}
//result: none
// a1fj391
}
static Regex MyRegex = new Regex(
"description:\\s*(?<value>[\\d\\w]+)",
RegexOptions.Compiled);
IEnumerable<string> getDescriptions(string html)
{
foreach(Match match in MyRegex.Matches(html))
{
yield return match.Groups["value"].Value;
}
}
Adapted From Code Project
string value = "ABC - UPDATED";
int index = value.IndexOf(" - UPDATED");
if (index != -1)
{
value = value.Remove(index);
}
It will print ABC without - UPDATED

Using Regex to alter a string in C# (based on ActionScript function)

I have some ActionScript code that splits a string using Regular Expression and lets me add content at the split location.
// AS3 Code
function formatTweetText(tweet:String ):String
{
var regUrl:RegExp = /http:\/\/\S+/g;
var _text:String = " "+ tweet + " ";
_text = _text.replace(regUrl, '<font color="#666666"> $&</font>');
_text = _text.substr(1, _text.length-2);
return _text;
}
I'm trying to find the C# equivalent to the above function
What this does is give you the entire text value inserting the Replacement text where the regular expression finds a match.
For example:
var text:String = "Hello there http://www.url.com";
would turn into
var newString:String = "hello there <font color="#666666"> http://www.url.com</font>"
using System.Text.RegularExpressions;
private string formatTweetText(string tweet)
{
string newText = " " + Regex.Replace(tweet, "/http:\/\/\S+/g", "Replacement String") + " ";
return newText.SubString(1, (newText.Length - 2));
}
Regex regUrl = new Regex(#"http://\S+");
string url = regUrl.Match(tweet).Value;
return string.Format("<font color=\"#666666\"> {0}</font>", url);
Using a combination of the answers, here is the function in C# that does the same thing as the ActionScript function.
private string formatTweetText(string tweet)
{
Regex regUrl = new Regex(#"http://\S+");
string url = regUrl.Match(tweet).Value;
if (url.Length > 0)
{
string newReturnVal = string.Format("<font color=\"#FF0000\">{0}</font>", url);
string returnVal = tweet.Replace(url, newReturnVal);
return returnVal;
}
else
{
return tweet;
}
}
The above code only works on the first match, if you have multiple matches you'll need to use this code:
private string formatTweetText(string tweet)
{
string returnVal = tweet;
string updatedValue = tweet;
Regex regUrl = new Regex(#"http://\S+");
Match matches = regUrl.Match(tweet);
while (matches.Success)
{
for (int i = 0; i <= 2; i++)
{
Group g = matches.Groups[i];
CaptureCollection cc = g.Captures;
for (int j = 0; j < cc.Count; j++)
{
Capture c = cc[j];
string url = c.Value;
if (c.Length > 0)
{
string newReturnVal = string.Format("<font color=\"#FF0000\">{0}</font>", url);
returnVal = updatedValue.Replace(url, newReturnVal);
}
updatedValue = returnVal;
}
}
matches = matches.NextMatch();
}
return returnVal;
}
Like this?
string FormatTweetText(string tweet)
{
string regUrl = "http:\/\/\S+";
string text = " " + tweet + " ";
text = Regex.Replace(text, regUrl,
"<font color=\"#666666\"> $&</font>");
text = text.Substring(1, text.Length - 2);
return text;
}

Categories