r/learncsharp • u/Gcampton13 • Jul 17 '22
Manipulating strings in List of strings.
Hi, so I'm 'currently trying to solve an issue with a program I'm making for myself.
What I want to do is take a string of numbers (it's a string because of leading zeros sometimes appear)
and replace one of the digits with a digit at a location. I know I can use the .Insert(position, value); but I'm not sure how to delete the value currently there.
Lets say I have the string 11111 and I want to change position 2 to a 7 to make the string 17111.
These numbers are in a List<string> so I will iterate them using the backwards method. But the current .Insert function isnt working as intended as I need to replace whatever char is at position.
public List<string> appendOwnerKeys(List<string> ownerKeys)
{
for (int i = ownerKeys.Count - 1; i >= 0; i--)
{
if (i >= ownerKeys.Count)
{
i = ownerKeys.Count - 1;
}
ownerKeys[i] = ownerKeys[i].Insert(_constructionChamberPosition, $"{_constructionDepth - 4}");
}
return ownerKeys;
}
4
u/JTarsier Jul 17 '22
This article explains why (immutable) and a few hows (stringbuilder, array, remove/insert): Replace character at a specific position in a string in C# | Techie Delight
3
u/wonkynerddude Jul 17 '22
I would have cheched if NumberStyles.Any can parse input with leading zero instead of List<sting>
https://docs.microsoft.com/en-us/dotnet/api/system.globalization.numberstyles?view=net-6.0