3

I want to remove all '\0' characters from the items of an ArrayList in c#. Here is my code:

ArrayList users = um.getAllUsers(server,Instance); //user count=3

So now I want to add a code in order to replase all '\0' with empty string in all the items of the list.

Is this possible?

1
  • 4
    What type is a user? A string? Commented Aug 4, 2010 at 10:15

3 Answers 3

4

First, it's a little odd to still be using ArrayList in 2010... and also to have Camel cased names (getAllUsers rather than GetAllUsers) but still...

for (int i = 0; i < users.Count; i++)
{
    string user = (string) users[i];
    user = user.Replace("\0", "");
    users[i] = user;
}
Sign up to request clarification or add additional context in comments.

2 Comments

It properly don't matter in this case, but I would use if (user == "\0") user = string.Empty instead of a .Replace because it not only replaces if the string is = "\0".
@lasseespeholt: It's not clear what the question actually means - whether it's meant to only replace "\0" for a whole item, or within each item.
2

If you're not stuck with some ancient version of .NET, you might be interested in upgrading your code to use the generic List<T> collection and have a look at LINQ:

List<string> users = um.getAllUsers(server,Instance)
                       .Cast<string>()
                       .Select(user => user.Replace("\0", ""))
                       .ToList();

(I assume getAllUsers returns an ArrayList containing string instances).

Comments

0

yes you can, simply call the replace method like that :

ArrayList users = um.getAllUsers(server,Instance);

for (int i = 0; i < users.Count; i++)
{
    users[i] = ((String) users[i]).Replace ("\0", "");
}

But I would suggest to use List instead of ArrayList if you can. Generics are good for you :-)

1 Comment

(Commenting one of you answers because I can't private message you): You suggested an edit on one of my answers that got rejected before I could accept it. (About using MemoryStream.ToArray() rather than MemoryStream.GetBuffer()). You're suggestion was correct, and I have manually changed my answer to follow your advice. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.