Is there an easy way to remove the first 2 and last 2 chars in a string?
I have this string:
\nTESTSTRING\n
How could I easily delete them?
Is there an easy way to remove the first 2 and last 2 chars in a string?
I have this string:
\nTESTSTRING\n
How could I easily delete them?
str = str.SubString(2,str.Length-4)
Of course you must test that the string contains more than 4 chars before doing this. Also in your case it seems that \n is a single newline character. If all you want to do is remove leading and trailing whitespaces, you should use
str.Trim()
as suggested by Charles
// Test string
var str = "\nTESTSTRING\n";
// Number of characters to remove on each end
var n = 2;
// Slimmed string
string slimmed;
if (str.Length > n * 2)
slimmed = str.Substring(n, str.Length - (n * 2));
else
slimmed = string.Empty;
// slimmed = "ESTSTRIN"
Papuccino1,
If you create an extension method like this:
public static class StringEnumerator {
public static IEnumerable<String> GetLines(this String source) {
String line = String.Empty;
StringReader stringReader = new StringReader(source);
while ((line = stringReader.ReadLine()) != null) {
if (!String.IsNullOrEmpty(line)) {
yield return line;
}
}
}
}
your code will be simplified and will be safer (not depending on dangerous index):
class Program {
static void Main(string[] args) {
String someText = "\nTESTSTRING\n";
String firstLine = someText.GetLines().First();
}
}
I hope this helps,
Ricardo Lacerda Castelo Branco