Change part of one string.

Hi developers!

I have one string of my database, I use this to read if the user has a item.
The string its “0000000”

If the user has the object with IDObject 3 and the object with IDObject 5 so the string its “0010100”
I can read this from database, but I don’t know how to modify part of the string to update the data.

I think in one function like this.

void PurchaseCard(int Card){
//when I call the function I want to make the entry number
//find this position in the string to change the number 0 to 1
string X = 1;
//Get the position 6 on my string and modify them like this
StringDB = "00000X0";
NewString = "0000010"; //And with this I can send to the DB
}
PurchaseCard(6)

Strings are immutable in C# so what you do is chop off the first part, put in your 1, and then add your last part, making a new string.

Off the top of my head:

int Card =  ???;

string data = "00000000";   // how it comes out of the database

// chop chop chop
data = data.Substring( 0, Card - 1) + "1" + data.Substring( Card + 1);

That might be off by one, I just typed it, didn’t run it. Verify with some graph paper and some numbers… :slight_smile:

Be aware also:

  • be consistent which side is the lowest value (left endian or right endian)

  • be consistent whether the lowest value is 0 or 1. Tradition favors 0 as “the first card” but your code looks like it might be 1-based.

ALL OF THAT being said, it might be better to have a generic “load from the database” function that returns an array of booleans, and then you set/clear the boolean at the index you care about, then you have another function that sticks that array back into the database, making it a string first. If you hide all that in one part of your code, you can later change it without much fuss.

Thanks, I’m thinking on use substring function and get 2 strings and add the STRING 1 in the middle of the 2 created strings and get the final string with this

StringBuilder is recommended for these operations. From the outside, it allows you to dynamically build your string.

1 Like

If you’re saving the item state as a bitmask, why not store the field as an integer and read/set the values directly using bitwise operations? If you have more than 32 items, you probably would want a more comprehensive structure than just a bitmask anyway.

Or if you’re stuck using a string, you can convert it to an int from binary using the Convert class, then convert it back once you’re done manipulating it.