C
C#3y ago
Grin

Is it possible to subtract a character from a string?

I've found that I can add strings, but can't figure out how to subtract strings, or characters from strings. Is there a function already in existence that can erase a character from a string, or replace the index of a string with a letter?
15 Replies
mtreit
mtreit3y ago
Strings are immutable but you can call methods like Replace or Substring to make a new string with changed content.
Grin
GrinOP3y ago
thank you I will check them out
mtreit
mtreit3y ago
If you need to replace characters by index you can also convert to a char array, update that, and then make a new string from the result.
MODiX
MODiX3y ago
mtreit#6470
REPL Result: Success
var s = "ABC";
var chars = s.ToCharArray();
chars[1] = '1';
var s2 = new string(chars);

Console.WriteLine(s2);
var s = "ABC";
var chars = s.ToCharArray();
chars[1] = '1';
var s2 = new string(chars);

Console.WriteLine(s2);
Console Output
A1C
A1C
Compile: 543.859ms | Execution: 73.735ms | React with ❌ to remove this embed.
Grin
GrinOP3y ago
neat I think thats what I needed I gotta ask about the var I've noticed that alot here, I like setting my stuff up as ints, chars, strings but it seems professionals only use var is that common practice
mtreit
mtreit3y ago
If it's obvious from the right side of the equal sign what the type is, then var is just more concise and in my opinion easier to read. It is especially the case with things like generic type declarations:
Dictionary<string, List<HashSet<string>>> map = new Dictionary<string, List<HashSet<string>>>();
Dictionary<string, List<HashSet<string>>> map = new Dictionary<string, List<HashSet<string>>>();
vs.
var map = Dictionary<string, List<HashSet<string>>>();
var map = Dictionary<string, List<HashSet<string>>>();
If you're really hardcore like @Jayy you actually enforce the use of var and don't let anything be checked in that doesn't use it. I think that's a rather extreme position and I'm not in favor of that myself.
Jayy
Jayy3y ago
It's great
Grin
GrinOP3y ago
lol
Jayy
Jayy3y ago
Editorconfig is smart enough that it only fails if you CAN use var And it's language version specific We got a bunch of new failures when i bumped us to c# 10 and suddenly a lot of lhs explicitly typed lambdas started failing Cuz c# could infer it now
Grin
GrinOP3y ago
sounds complicated
Jayy
Jayy3y ago
I mean not really lol
Grin
GrinOP3y ago
hope I'll be able to understand that lingo soon
Jayy
Jayy3y ago
Took maybe 30 seconds to fix it
mtreit
mtreit3y ago
Explicitly typed lambda meaning like Func<int, int> xyz = // something ? Or do you mean something else?
Jayy
Jayy3y ago
Yee that We have a shitty retry function that's used all over the places that needs that pattern
Want results from more Discord servers?
Add your server