The program should return edit text, where you have to replace" - ", ": ", "; ", ", ", " " with "\t".
The problem here is the result
Input: Китай: 1405023000; 24.08.2020; 17.99%
Expected Китай 1405023000 24.08.2020 17.99%
Myne Китай: 1405023000; 24.08.2020; 17.99%
So for some reason, I believe he messing with the order of `stringSeparators` elements or what. I am interested in this moment
public static string ReplaceIncorrectSeparators(string text)
{
string populationEdited = "";
string[] stringSeparators = new string[] {" - ", ": ", "; ", ", ", " "};
for (int i = 0; i < stringSeparators.Length; i++)
{
populationEdited = text.Replace(stringSeparators[i], "\t");
}
return populationEdited;
}
I've already solved the problem in another way but I want to solve it with separators.
The main problem in your code is that it doesn't store the result of Replace properly. This should do the trick:
public static string ReplaceIncorrectSeparators(string text)
{
string populationEdited = text; // You need to start with the original
string[] stringSeparators = new string[] {" - ", ": ", "; ", ", ", " "};
for (int i = 0; i < stringSeparators.Length; i++)
{
// And here instead of text.Replace you do populationEdited.Replace
populationEdited = populationEdited.Replace(stringSeparators[i], "\t");
}
return populationEdited;
}
You could Regex as an alternative. It would make your code shorter (an in my opinion more readable).
public static string ReplaceIncorrectSeparators(string text)
{
Regex regex = new Regex(#" - |: |; |, | ");
return regex.Replace(text, "\t");
}
Related
I created a small function to catch a string between strings.
public static string[] _StringBetween(string sString, string sStart, string sEnd)
{
if (sStart == "" && sEnd == "")
{
return null;
}
string sPattern = sStart + "(.*?)" + sEnd;
MatchCollection rgx = Regex.Matches(sString, sPattern);
if (rgx.Count < 1)
{
return null;
}
string[] matches = new string[rgx.Count];
for (int i = 0; i < matches.Length; i++)
{
matches[i] = rgx[i].ToString();
//MessageBox.Show(matches[i]);
}
return matches;
}
However if i call my function like this: _StringBetween("[18][20][3][5][500][60]", "[", "]");
It will fail. A way would be if i changed this line string sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd;
However i can not because i dont know if the character is going to be a bracket or a word.
Sorry if this is a stupid question but i couldn't find something similar searching.
A way would be if i changed this line string sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd; However i can not because i don't know if the character is going to be a bracket or a word.
You can escape all meta-characters by calling Regex.Escape:
string sPattern = Regex.Escape(sStart) + "(.*?)" + Regex.Escape(sEnd);
This would cause the content of sStart and sEnd to be interpreted literally.
I'm trying to replace a string in C# with the class Regex but I don't know use the class properly.
I want replace the next appearance chain in the String "a"
":(one space)(one or more characters)(one space)"
by the next regular expression
":(two spaces)(one or more characters)(three spaces)"
Will anyone help me and give me the code and explains me the regular expresion used?
you can use string.Replace(string, string)
try this one.
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
try this one
private String StrReplace(String Str)
{
String Output = string.Empty;
String re1 = "(:)( )((?:[a-z][a-z]+))( )";
Regex r = new Regex(re1, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match m = r.Match(Str);
if (m.Success)
{
String c1 = m.Groups[1].ToString();
String ws1 = m.Groups[2].ToString() + " ";
String word1 = m.Groups[3].ToString();
String ws2 = m.Groups[4].ToString() + " ";
Output = c1.ToString() + ws1.ToString() + word1.ToString() + ws2.ToString() + "\n";
Output = Regex.Replace(Str, re1, Output);
}
return Output;
}
Using String.Replace
var str = "Test string with : .*. to replace";
var newstr = str.Replace(": .*. ", ": .*. ");
Using Regex.Replace
var newstr = Regex.Replace(str,": .*. ", ": .*. ");
I am trying to highlight search terms in display results. Generally it works OK based on code found here on SO. My issue with it is that it replaces the substring with the search term, i.e. in this example it will replace "LOVE" with "love" (unacceptable). So I was thinking I probably want to find the index of the start of the substring, do an INSERT of the opening <span> tag, and do similar at the end of the substring. As yafs may be quite long I'm also thinking I need to integrate stringbuilder into this. Is this do-able, or is there a better way? As always, thank you in advance for your suggestions.
string yafs = "Looking for LOVE in all the wrong places...";
string searchTerm = "love";
yafs = yafs.ReplaceInsensitive(searchTerm, "<span style='background-color: #FFFF00'>"
+ searchTerm + "</span>");
how about this:
public static string ReplaceInsensitive(string yafs, string searchTerm) {
return Regex.Replace(yafs, "(" + searchTerm + ")", "<span style='background-color: #FFFF00'>$1</span>", RegexOptions.IgnoreCase);
}
update:
public static string ReplaceInsensitive(string yafs, string searchTerm) {
return Regex.Replace(yafs,
"(" + Regex.Escape(searchTerm) + ")",
"<span style='background-color: #FFFF00'>$1</span>",
RegexOptions.IgnoreCase);
}
Check this code
private static string ReplaceInsensitive(string text, string oldtext,string newtext)
{
int indexof = text.IndexOf(oldtext,0,StringComparison.InvariantCultureIgnoreCase);
while (indexof != -1)
{
text = text.Remove(indexof, oldtext.Length);
text = text.Insert(indexof, newtext);
indexof = text.IndexOf(oldtext, indexof + newtext.Length ,StringComparison.InvariantCultureIgnoreCase);
}
return text;
}
Does what you need:
static void Main(string[] args)
{
string yafs = "Looking for LOVE in all the wrong love places...";
string searchTerm = "LOVE";
Console.Write(ReplaceInsensitive(yafs, searchTerm));
Console.Read();
}
private static string ReplaceInsensitive(string yafs, string searchTerm)
{
StringBuilder sb = new StringBuilder();
foreach (string word in yafs.Split(' '))
{
string tempStr = word;
if (word.ToUpper() == searchTerm.ToUpper())
{
tempStr = word.Insert(0, "<span style='background-color: #FFFF00'>");
int len = tempStr.Length;
tempStr = tempStr.Insert(len, "</span>");
}
sb.AppendFormat("{0} ", tempStr);
}
return sb.ToString();
}
Gives:
Looking for < span style='background-color: #FFFF00'>LOVE< /span> in all the wrong < span style='background-color: #FFFF00'>love< /span> places...
I have a string like this:
“I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.”
I want to insert <strong> around the "a" in "a diplomatic", but nowhere else.
What I have as input is diplomatic from a previous function, and I wan't to add <strong>to the closest instance of "a".
Right now, of course when I use .Replace("a", "<strong>a</strong>"), every single instance of "a" receives the <strong>-treatment, but is there any way to apply this to just to one I want?
Edit
The string and word/char ("a" in the case above) could be anything, as I'm looping through a lot of these, so the solution has to be dynamic.
var stringyourusing = "";
var letter = "";
var regex = new Regex(Regex.Escape(letter));
var newText = regex.Replace(stringyourusing , "<strong>letter</strong>", 1);
Would this suffice?
string MakeStrongBefore(string strong, string before, string s)
{
return s.Replace(strong + " " + subject, "<strong>" + strong + "</strong> " + before);
}
Used like this:
string s = “I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.”;
string bolded = MakeStrongBefore("a", "diplomatic", s);
Try this:
public string BoldBeforeString(string source, string bolded,
int boldBeforePosition)
{
string beforeSelected = source.Substring(0, boldBeforePosition).TrimEnd();
int testedWordStartIndex = beforeSelected.LastIndexOf(' ') + 1;
string boldedString;
if (beforeSelected.Substring(testedWordStartIndex).Equals(bolded))
{
boldedString = source.Substring(0, testedWordStartIndex) +
"<strong>" + bolded + "</strong>" +
source.Substring(testedWordStartIndex + bolded.Length);
}
else
{
boldedString = source;
}
return boldedString;
}
string phrase = "I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.";
string boldedPhrase = BoldBeforeString(phrase, "a", 41);
Hei!
I've tested this and it works:
String replaced = Regex.Replace(
"I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.",
#"(a) diplomatic",
match => "<strong>" + match.Result("$1") + "</strong>");
So to make it a general function:
public static String StrongReplace(String sentence, String toStrong, String wordAfterStrong)
{
return Regex.Replace(
sentence,
#"("+Regex.Escape(toStrong)+") " + Regex.Escape(wordAfterStrong),
match => "<strong>" + match.Result("$1") + "</strong>");
}
Usage:
String sentence = "I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.";
String replaced = StrongReplace(sentence, "a", "diplomatic");
edit:
considering your other comments, this is a function for placing strong tags around each word surrounding the search word:
public static String StrongReplace(String sentence, String word)
{
return Regex.Replace(
sentence,
#"(\w+) " + Regex.Escape(word) + #" (\w+)",
match => "<strong>" + match.Result("$1") + "</strong> " + word + " <strong>" + match.Result("$2") + "</strong>");
}
I am trying to write a function that as input takes a string containing words and removes all single character words and returns the new string without the removed characters
E.g.:
string news = FunctionName("This is a test");
//'news' here should be "This is test".
Can you please help?
Obligatory LINQ one-liner:
string.Join(" ", "This is a test".Split(' ').Where(x => x.Length != 1).ToArray())
Or as a nicer extension method:
void Main()
{
var output = "This is a test".WithoutSingleCharacterWords();
}
public static class StringExtensions
{
public static string WithoutSingleCharacterWords(this string input)
{
var longerWords = input.Split(' ').Where(x => x.Length != 1).ToArray();
return string.Join(" ", longerWords);
}
}
I'm sure there's a nicer answer using regex, but you could do the following:
string[] words = news.Split(' ');
StringBuilder builder = new StringBuilder();
foreach (string word in words)
{
if (word.Length > 1)
{
if (builder.ToString().Length ==0)
{
builder.Append(word);
}
else
{
builder.Append(" " + word);
}
}
}
string result = builder.ToString();
The interesting thing about this question is that presumably you also want to remove one of the spaces surrounding the single-letter word.
string[] oldText = {"This is a test", "a test", "test a"};
foreach (string s in oldText) {
string newText = Regex.Replace(s, #"\s\w\b|\b\w\s", string.Empty);
WL("'" + s + "' --> '" + newText + "'");
}
Output...
'This is a test' --> 'This is test'
'a test' --> 'test'
'test a' --> 'test'
With Linq syntax, you could do something like
return string.Join(' ', from string word in input.Split(' ') where word.Length > 1))
string str = "This is a test.";
var result = str.Split(' ').Where(s => s.Length > 1).Aggregate((s, next) => s + " " + next);
UPD
Using the extension method:
public static string RemoveSingleChars(this string str)
{
return str.Split(' ').Where(s => s.Length > 1).Aggregate((s, next) => s + " " + next);
}
//----------Usage----------//
var str = "This is a test.";
var result = str.RemoveSingleChars();