2

This is a pretty basic question, but here it goes: Is there a string method in C# that adds a number of characters from a string to another string? In C++ std::string class, there was the append method that had three parameters: source string, indexStart, offset.

string a = "foo";
string b = "bar";

a.append(b, 0, 2); // a is now "fooba";

In C# I also tried with StringBuilder, but no luck.

0

4 Answers 4

5

Strings in .NET are immutable. Once a string is created, you can't modify it. However, you can create a new string by concatenation, and reassign it to the same variable:

string a = "foo";
string b = "bar";

a = a + b.Substring(0, 2); // a is now "fooba";
Sign up to request clarification or add additional context in comments.

Comments

4
string a = "foo";
string b = "bar";

var sb = new StringBuilder();
sb.append(a);
sb.append(b.SubString(0,2));

string res = sb.ToString(); // res = "fooba"

Comments

4

If you're feeling adventurous, you could also write an extension method:

public static class MyStringExtensions
{
    public static string Append(this string original, string textToAdd, int length)
    {
        if (length <= 0)
        {
            return original;
        }

        var len = (textToAdd.Length < length)
                      ? textToAdd.Length
                      : length;

        return original + textToAdd.Substring(0, len);
    }
}

Then to use it you would go like this:

string a = "foo".Append("bar", 2);

or

string a = "foo";
string b = "bar";
string c = a.Append(b, 2);

This also has the nice advantage of allowing error/exception handling in a central location.

2 Comments

Now, that's really sweet! Thanks! :)
Definitely a nice feature of c#.
2

Try doing

 string aa = "foo";
            string bb = "bad";
            bb= string.Concat(aa, bb.Substring(0, 2));

Comments

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.