C# Basic
C# String Copy() Method
Photo Credit to CodeToFun
đ Introduction
In C# programming, the Copy()
method is a useful feature provided by the System.String class for duplicating a portion of a string.
This method creates a new string with a specified length, starting from a specified position in the existing string.
In this tutorial, we'll explore the syntax, usage, and functionality of the Copy()
method in C#.
đĄ Syntax
The syntax for the Copy()
method is as follows:
public string Copy(int startIndex, int length);
- startIndex: The starting index in the current string from which to begin copying characters.
- length: The number of characters to copy.
The method returns a new string containing the specified substring.
đ Example
using System;
class Program {
static void Main() {
string s1 = "Hello ";
string s2 = string.Copy(s1);
Console.WriteLine(s1);
Console.WriteLine(s2);
}
}
đģ Testing the Program
Hello Hello
đ§ How the Program Works
In this example, the Copy()
method is used to create a new string starting from the index 3 (inclusive) of the original string "C# Programming" with a length of 10 characters.
âŠī¸ Return Value
The Copy()
method returns a new string that is a copy of the specified portion of the original string.
đ Common Use Cases
The Copy()
method is particularly useful when you need to extract a substring from an existing string, creating a new string with specific content. This is valuable for various string manipulation tasks.
đ Notes
- If the combination of startIndex and length exceeds the length of the original string, the method copies until the end of the string.
- If startIndex is beyond the length of the string, an ArgumentOutOfRangeException is thrown.
- If length is negative, an ArgumentOutOfRangeException is thrown.
đĸ Optimization
The Copy()
method is optimized for performance, and no specific optimization is required. Ensure that the specified indices are within the bounds of the string to avoid exceptions.
đ Conclusion
The Copy()
method in C# provides a straightforward way to create a new string by copying a specified portion of an existing string. Whether you need to extract substrings for manipulation or create variations of strings, the Copy()
method is a valuable tool.
Feel free to experiment with different combinations of startIndex and length to explore the behavior of the Copy()
method in various scenarios. Happy coding!
đ¨âđģ Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (C# String Copy() Method), please comment here. I will help you immediately.