简体   繁体   中英

Copy part of a string to another string in C#

I'm trying to copy part of the text from text box to another string. For example if my textbox contain 10 characters, I want to copy from character 3 to character 7 to another string call TEST. How do we do it?

// Start at the 2nd index (0=based index)
// Take  from the 3rd to the 7th character, 
string test = textBox.Text.Substring(2, 5);
// when textbox contains "ABCDEFGHIJ", the result will be "CDEFG"
string result = textBox.Text.Substring(2, 5);

Keep in mind that this will throw an exception for strings shorter than 7 characters, so you may want to add some length checks.

I think the method you are looking for is Substring. With this method you can get any part of a string starting form a certain index.

For Example:

string test = YourTextBox.Text.Substring(2, 5);

In this example you'll get foru characters of the string in YourTextBox starting at index 2.

Here you go

string test = TakePieceFromText("this is my data to work with", 2, 5);

/// <summary>
/// Takes the piece from text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="length">The length.</param>
/// <returns>a piece of text</returns>
private string TakePieceFromText(string text, int startIndex, int length)
{
    if (string.IsNullOrEmpty(text))
        throw new ArgumentNullException("no text givin");

    string result = string.Empty;
    try
    {
        result = text.Substring(startIndex, length);
    }
    catch (Exception ex)
    { 
     // log exception
    }
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM