I am need to highlight the keywords or tags in an article & pass variable to jQuery Array
i am using property to pass value from C# to java-script which works i also need to format my keywords which in database are stored like one, two, three, four, five,six,seven
in order to make it work i have to wrap each keyword in single ' or double quotes".
JQuery
function HighlightKeywords(keywords) {
var el = $("body");
$(keywords).each(function () {
var pattern = new RegExp("(" + this + ")", ["gi"]);
var rs = "<a href='search.aspx?search=$1'<span style='background-color:#FFFF00;font-weight: bold;background-color:#FFFF00;'>$1</span></a>";
el.html(el.html().replace(pattern, rs));
});
}
HighlightKeywords(["<%= MyProperty %>]");
C# Code
string _sFinalList = null;
protected string MyProperty { get { return _sFinalList; } }
string sKewords = "one, two, three, four, five,six,seven";
List<string> lstKewords = sKewords.Split(',').ToList();
foreach (string list in lstKewords) // Loop through List with foreach
{
_sFinalList += "'" + list + "',";
}
Problem with this code is that it ads , after the last words i want to know what is the best way to avoid adding , after the last words
Current OUTPUT: "'one', 'two', 'three', 'four', 'five','six','seven',"
Desired OUTPUT: "'one', 'two', 'three', 'four', 'five','six','seven'"
Help in this regard is appreciated
In C#, use String.Join() :
List<string> lstKeywords = sKeywords.Split(',').ToList();
var quotedKeywords = lstKeywords.Select(s => "'" + s + "'");
string _sFinalList = string.Join(",", quotedKeywords);
You can using String.Join()
string sKewords = "one, two, three, four, five,six,seven";
List<string> lstKewords = sKewords.Split(',').ToList();
var _partial = lstKewords.Select(x => "'" + x + "'");
Var _result = String.Join(",", _partial);
String.Join()
You could use String.Join
var result = string.Format("'{0}'", string.Join("','", yourList));
you may simply remove lastIndexOf(",") with substring function of string class after you complete the for loop.
OR
you may add and if statement in your for loop that would add "," if loop is not in its last iteration.
Related
So im running a little issue with my code, how can I convert my List into a normal string with this format
listitem1, listitem2, listitem3
Note that last listitem3 does not have a , at the end.
I tried String.Inser but I cant get the last index..
Sound like you need string.Join
var result = string.Join(", ", yourList);
Use a join which will concatenate your array with a delimiter which you define.
Likewise use a split to turn your delimited spring into an array.
var list = new List<string> {"one", "two", "three"};
var stringList = string.Join(", ", list);
the result will be
one, two, three
If you want the space make sure to include it in the delimeter ", "
Or you can use a foreach loop, to get last item then based on that append a comma :
List<string> mylist = new List<string>();
mylist.Add("Test1");
mylist.Add("Test2");
mylist.Add("Test3");
string lastItem = mylist[mylist.Count - 1];
foreach(string s in mylist)
{
if (s != lastItem)
Console.Write(s + ", ");
else
Console.Write(s);
}
and the result is:
Test1, Test2, Test3
I want to have an string in this format
name1,date1|name2,date2
For that I have written a method
int ifirstStringLength = strFirstStringArray.Length;
int iSecondStringLength = strSecondStringArray.Length;
if (ifirstStringLength != iSecondStringLength)
throw new Exception("First and Second Array should be of same length");
for (int index = 0; index < ifirstStringLength; index++)
{
strCombinedString = strCombinedString + strFirstStringArray[index] + chrElementSeprator.ToString() + strSecondStringArray[index];
if (index < ifirstStringLength - 1)
strCombinedString = strCombinedString + chrItemSeperator.ToString();
}
return strCombinedString;
Question 1:
Is this a good way or any better way?
Question 2:
Any idea if I want to achieve this using linq/lambda expression?
Updated:
my inputs are
string[] names = {"name1","name2"};
string[] dates = {"date1","date2"};
sorry for miscommunication
Idea is to split names and dates separately, then zip two sequences, combining name-date pair one at a time. After that join each pair with '|' symbol
string[] names = {"name1", "name2"};
string[] dates = {"date1", "date2"};
var pairs = names.Zip(dates, (name, date) => name + "," + date);
string result = string.Join("|", pairs);
Console.WriteLine(result);
prints:
name1,date1|name2,date2
Your code seems needlessly complex to me. Not entirely sure this will meet all of your requirements but I would do something like this;
//assuming both strings are comma delimited
string[] nameTokens = nameString.Split(',');
string[] dateTokens = dateString.Split(',');
string result;
if (nameTokens.Length == 2 && dateTokens.Length == 2)
result = String.Format("{1},{2}|{3},{4}", nameTokens[0], dateTokens[0], nameTokens[1], dateTokens[1]);
else
Console.WriteLine("BAD INPUT");
Explanation; I start by splitting the name and date strings so I have two strings arrays. Then I check the lengths to make sure they each have 2 elements (prevent array out of bounds exceptions). After that I use the String.Format method to create a new string in the specified format. There are shorter solutions available using LINQ however, this ensures that you don't get an array out of bounds exception and could not be more straight forward.
You could use LINQ's Select method. One of the overloads takes a Func<TSource, Int32, TResult>. This gives you the index of the current string in the array.
var result = string.Join("|",
names.Select((s, index) => string.Format("{0},{1}", s, dates[index])));
string strCombinedString = strFirstStringArray.Select((S, i) => "|" + S + "," + strSecondStringArray[i]).Aggregate((Result, Item) => Result += Item);
strCombinedString.Remove(0, 1);
What i'm trying to do is split a string backwards. Meaning right to left.
string startingString = "<span class=\"address\">Hoopeston,, IL 60942</span><br>"
What I would do normally is this.
string[] splitStarting = startingString.Split('>');
so my splitStarting[1] would = "Hoopeston,, IL 60942</span"
then I would do
string[] splitAgain = splitStarting[1].Split('<');
so splitAgain[0] would = "Hoopeston,, IL 60942"
Now this is what I want to do, I want to split by ' ' (a space) reversed for the last 2 instances of ' '.
For example my array would come back like so:
[0]="60942"
[1]="IL"
[2] = "Hoopeston,,"
To make this even harder I only ever want the first two reverse splits, so normally I would do something like this
string[] splitCity,Zip = splitAgain[0].Split(new char[] { ' ' }, 3);
but how would you do that backwards? The reason for that is, is because it could be a two name city so an extra ' ' would break the city name.
Regular expression with named groups to make things so much simpler. No need to reverse strings. Just pluck out what you want.
var pattern = #">(?<city>.*) (?<state>.*) (?<zip>.*?)<";
var expression = new Regex(pattern);
Match m = expression .Match(startingString);
if(m.success){
Console.WriteLine("Zip: " + m.Groups["zip"].Value);
Console.WriteLine("State: " + m.Groups["state"].Value);
Console.WriteLine("City: " + m.Groups["city"].Value);
}
Should give the following results:
Found 1 match:
1. >Las Vegas,, IL 60942< has 3 groups:
1. Las Vegas,, (city)
2. IL (state)
3. 60942 (zip)
String literals for use in programs:
C#
#">(?<city>.*) (?<state>.*) (?<zip>.*?)<"
One possible solution - not optimal but easy to code - is to reverse the string, then to split that string using the "normal" function, then to reverse each of the individual split parts.
Another possible solution is to use regular expressions instead.
I think you should do it like this:
var s = splitAgain[0];
var zipCodeStart = s.LastIndexOf(' ');
var zipCode = s.Substring(zipCodeStart + 1);
s = s.Substring(0, zipCodeStart);
var stateStart = s.LastIndexOf(' ');
var state = s.Substring(stateStart + 1);
var city = s.Substring(0, stateStart );
var result = new [] {zipCode, state, city};
Result will contain what you requested.
If Split could do everything there would be so many overloads that it would become confusing.
Don't use split, just custom code it with substrings and lastIndexOf.
string str = "Hoopeston,, IL 60942";
string[] parts = new string[3];
int place = str.LastIndexOf(' ');
parts[0] = str.Substring(place+1);
int place2 = str.LastIndexOf(' ',place-1);
parts[1] = str.Substring(place2 + 1, place - place2 -1);
parts[2] = str.Substring(0, place2);
You can use a regular expression to get the three parts of the string inside the tag, and use LINQ extensions to get the strings in the right order.
Example:
string startingString = "<span class=\"address\">East St Louis,, IL 60942</span><br>";
string[] city =
Regex.Match(startingString, #"^.+>(.+) (\S+) (\S+?)<.+$")
.Groups.Cast<Group>().Skip(1)
.Select(g => g.Value)
.Reverse().ToArray();
Console.WriteLine(city[0]);
Console.WriteLine(city[1]);
Console.WriteLine(city[2]);
Output:
60942
IL
East St Louis,,
How about
using System.Linq
...
splitAgain[0].Split(' ').Reverse().ToArray()
-edit-
ok missed the last part about multi word cites, you can still use linq though:
splitAgain[0].Split(' ').Reverse().Take(2).ToArray()
would get you the
[0]="60942"
[1]="IL"
The city would not be included here though, you could still do the whole thing in one statement but it would be a little messy:
var elements = splitAgain[0].Split(' ');
var result = elements
.Reverse()
.Take(2)
.Concat( new[ ] { String.Join( " " , elements.Take( elements.Length - 2 ).ToArray( ) ) } )
.ToArray();
So we're
Splitting the string,
Reversing it,
Taking the two first elements (the last two originally)
Then we make a new array with a single string element, and make that string from the original array of elements minus the last 2 elements (Zip and postal code)
As i said, a litle messy, but it will get you the array you want. if you dont need it to be an array of that format you could obviously simplfy the above code a little bit.
you could also do:
var result = new[ ]{
elements[elements.Length - 1], //last element
elements[elements.Length - 2], //second to last
String.Join( " " , elements.Take( elements.Length - 2 ).ToArray( ) ) //rebuild original string - 2 last elements
};
At first I thought you should use Array.Reverse() method, but I see now that it is the splitting on the ' ' (space) that is the issue.
Your first value could have a space in it (ie "New York"), so you dont want to split on spaces.
If you know the string is only ever going to have 3 values in it, then you could use String.LastIndexOf(" ") and then use String.SubString() to trim that off and then do the same again to find the middle value and then you will be left with the first value, with or without spaces.
Was facing similar issue with audio FileName conventions.
Followed this way: String to Array conversion, reverse and split, and reverse each part back to normal.
char[] addressInCharArray = fullAddress.ToCharArray();
Array.Reverse(addressInCharArray);
string[] parts = (new string(addressInCharArray)).Split(new char[] { ' ' }, 3);
string[] subAddress = new string[parts.Length];
int j = 0;
foreach (string part in parts)
{
addressInCharArray = part.ToCharArray();
Array.Reverse(addressInCharArray);
subAddress[j++] = new string(addressInCharArray);
}
Suppose I have a collection of strings:
"foo"
"bar"
"xyz"
And I would like to generate a comma separated values from the list into something like:
"foo, bar, xyz"
Notice the lack of ", " at the end.
I am aware that there are dozens of ways to generate this:
use for-loop and string.Format() or StringBuilder.
use integer counter and remove the ending ", " if the value > 0
don't put ", " on the first run
etc.
Sample code of what I have right now:
if (strs.Count() > 0)
{
var sb = new StringBuilder();
foreach (var str in strs)
sb.AppendFormat("{0}, ", str);
return sb.Remove(0, 2).ToString();
}
What is the best code that is highly reusable for the above scenario, and why?
You want to use the string.Join method, which exists in the BCL for this purpose.
Example:
var myArray = new string[] { "one", "two", "three" };
var output = string.Join(", ", myArray);
Or if you're using .NET 3.5, you can do this with any IEnumerable<string> as such:
var output = string.Join(", ", myEnumerable.ToArray());
(Note that this doesn't give the best performance as it requires, although it is clearly still 'O(n)', and should be suitable for almost all cases).
Now, if your enumerable is not of type string (generically an IEnumerable<T>), you can just use the Select method to convert the result into a string, e.g.
var output = string.Join(", ", myEnumerable.Select(e => e.ToString()).ToArray());
I'm not sure if you're dealing with values that may potentially contains commas in themselves, but this can be worked around by enclosing them in quotes (") and escaping the quotes, similarly to the CSV format.
var output = string.Join(", ", items.Select(x => x.Contains(",") ?
"\"" + x.Replace("\"", "\"\"") + "\"" : x);
Of course, splitting them back up again is a slightly triciker task, which requires a bit of regex.
String.Join is the right answer, but in the case of an IEnumerable, Linq is often shorter than a for loop:
someStringCollection.Aggregate((first, second) => first + ", " + second);
As others have said: String.Join is normally the best way to do this. But what if you have just have an IEnumerable rather than an array? Perhaps you have code to enumerate these as you read them from a file using deferred execution. In this case String.Join isn't quite as nice, because you have to loop over the strings twice — once to create the array and once to join it. In that case, you want something more like this:
public static string ToDelimitedString(this IEnumerable<string> source, string delimiter)
{
string d = "";
var result = new StringBuilder();
foreach( string s in source)
{
result.Append(d).Append(s);
d = delimiter;
}
return result.ToString();
}
This will perform almost as well as String.Join, and works in the more general case. Then, given a string array or any other IEnumerable you can call it like this:
string finalStr = MyStrings.ToDelimitedString(",");
string finalstr = String.Join(",", strs);
Use
string s = string.Join (",", new string[] {"aaa", "bbb", "ccc"});
Use String.Join
If you have an array of strings, go with Noldorin's solution.
But if it's some other collection type, I might do this:
if (strs.Count() > 0)
{
var sb = new StringBuilder();
foreach (var str in strs)
sb.AppendFormat("{0} {1}", (0 == sb.Length ? "" : ","), str);
return sb.ToString();
}
This is the Code for adding comma after another number, but I want to delete the last comma:
str_MSISDN.Append("'" + _MSISDN[x].TrimStart() + "'" + ",");
Instead of manually appending things, I suggest you use String.Join which will get it right to start with. You can use LINQ to do the trimming of the values. For example:
string x = string.Join(",", _MSISDN.Select(x => "'" + x.TrimStart() + "'")
.ToArray());
EDIT: A nicer version of this is available with MoreLINQ and its ToDelimitedString method:
string x = _MSISDN.Select(x => "'" + x.TrimStart() + "'")
.ToDelimitedString(",");
You can do that using the TrimEnd method (when you are done appending):
str_MSISDN = str_MSISDN.ToString().TrimEnd(',');
You can use the String.TrimEnd() method:
[your value] = str_MSISDN.ToString().TrimEnd(",".ToCharArray())
My favourite way of doing this kind of thing is to use the string.Join method:
string str_MSISDN = string.Join(", ", _MSISDN);
(assuming that _MSISDN is an array of strings)
If you want to trim the start of each item you can do this:
string str_MSISDN = string.Join(", ", _MSISDN.Select(x=>x.TrimStart()).ToArray());
Note how you have to call .ToArray since the Join method wants an array not an IEnumerable
I'd say don't add it in the first place, you've several options for doing this.
1) Use string.join
2) Restructure your loop as follows
int i = 0;
if (_MSISDN.Length > 0)
{
str_MSISDN.Append("'" + _MSISDN[i++].TrimStart() + "'")
while( i < _MSISDN.Length )
str_MSISDN.Append(",'" + _MSISDN[i++].TrimStart() + "'");
}