How can I get a character in a string by index?
string s = “hello”; char c = s[1]; // now c == ‘e’ See also Substring, to return more than one character.
string s = “hello”; char c = s[1]; // now c == ‘e’ See also Substring, to return more than one character.
The error message is misleading. What you actually need is to provide the compiler a way to compare two Meme instances and decide upon which criteria those instances are equal. Let’s say you want two instances having the same name property to be treated as equal. We make the struct conform to Equatable and we … Read more
string[] myarr = new string[] {“s”, “f”, “s”}; int[] v = myarr.Select((b,i) => b == “s” ? i : -1).Where(i => i != -1).ToArray(); This will return 0, 2 If the value does not exist in the array then it will return a int[0]. make an extension method of it public static class EM { … Read more
Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg or .html x.replace(/\.[^/.]+$/, “”)
I’d question the wisdom, but perhaps: source.TakeWhile(x => x != value).Count(); (using EqualityComparer<T>.Default to emulate != if needed) – but you need to watch to return -1 if not found… so perhaps just do it the long way public static int IndexOf<T>(this IEnumerable<T> source, T value) { int index = 0; var comparer = EqualityComparer<T>.Default; … Read more
You really could use the regular expression /((s).*?){n}/ to search for n-th occurrence of substring s. In C# it might look like this: public static class StringExtender { public static int NthIndexOf(this string target, string value, int n) { Match m = Regex.Match(target, “((” + Regex.Escape(value) + “).*?){” + n + “}”); if (m.Success) return … Read more
You can use indexOf: var imageList = [100,200,300,400,500]; var index = imageList.indexOf(200); // 1 You will get -1 if it cannot find a value in the array.
Instances of the String constructor have a .search() method which accepts a RegExp and returns the index of the first match. To start the search from a particular position (faking the second parameter of .indexOf()) you can slice off the first i characters: str.slice(i).search(/re/) But this will get the index in the shorter string (after … Read more
indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator). You cannot use === to check the equability of an object. As @RobG pointed out Note that by definition, two objects are never equal, even if they have exactly the same property names and … Read more
var str = “I learned to play the Ukulele in Lebanon.” var regex = /le/gi, result, indices = []; while ( (result = regex.exec(str)) ) { indices.push(result.index); } UPDATE I failed to spot in the original question that the search string needs to be a variable. I’ve written another version to deal with this case … Read more