C
C#2y ago
sonodan.

Searching a string for a substring containing operators

I'm trying to find how many times the string "*" occurs in a string I have. I've tried a few different things including backslashes, but I found a stackoverflow solution saying a string literal should work: var matches = response.Where(s => s.Contains(@""*"")).Count; I'm met with an error Operator * cannot be applied to operands of type 'string' and 'string'. What's the best practice here to accomplish this?
11 Replies
Thinker
Thinker2y ago
@""*"" doesn't make any sense It reads as (@"") * (""), and you can't multiply strings Just use "*", no need for the verbatim string.
MODiX
MODiX2y ago
thinker227#5176
REPL Result: Success
"1 * 2 * 3 * 4".Count(c => c == '*')
"1 * 2 * 3 * 4".Count(c => c == '*')
Result: int
3
3
Compile: 603.664ms | Execution: 61.216ms | React with ❌ to remove this embed.
Thinker
Thinker2y ago
or this
sonodan.
sonodan.2y ago
Hey, thanks for replying. To clarify, the substring I am looking for is "*", as opposed to just the char *
Thinker
Thinker2y ago
The char *? Discord's formatting is weird
sonodan.
sonodan.2y ago
example string: "I'm searching for "*" in this string" method should return a count of 1
Thinker
Thinker2y ago
Ah "*" as a string
sonodan.
sonodan.2y ago
yep! sorry hard to convey
Thinker
Thinker2y ago
Yeah, you have to escape the "s or use a verbatim string. "\"*\"" or @"""*""". In verbatim strings (preceded by the @), " characters are written as "" Otherwise you just escape them using \"
sonodan.
sonodan.2y ago
ahh so I was one set of "" off on the string literal. Thanks for the help!
Thinker
Thinker2y ago
Yeah, no problem catsip you can type /close to close the post.