Reputation: 16040
Given a string eg 500 chars and I want to pick a string between index 400 and index 430. How do you write such a function?
Thanks
Upvotes: 5
Views: 26663
Reputation: 1725
c# 8 has the useful range index method on string [n..L]
var example = "An extraordinary day dawns with each new day.";
Console.WriteLine(example[3..(15+1)]);
// extraordinary
//if you use ^ then it grabs the index from the end
Console.WriteLine(example[3..^5]);
// extraordinary day dawns with each new
specific to question
var result = example[400..(430+1)];
Upvotes: 0
Reputation: 21
string result = S.Substring(startIndex, startIndex - endIndex);
Upvotes: 2
Reputation: 3284
Not super important, just something to be aware of to avoid "off-by-one"-like errors.
Since you didn't explicitly state whether or not to include the endpoints,
yourString.Substring(400, 30)
won't give you only the characters between indices 400 and 430 (i.e. excluding index 400 and 430).
Instead, what you get is the substring composed of the characters from index 400 (inclusive) to index 429 (inclusive).
To actually get the string between two indices excluding the endpoints (resulting in a string composed of the characters from indices 401 to 429) you require something like:
yourString.Substring(beginIndex+1,endIndex-beginIndex-1);
And if you wanted to include both index 400 and 430 (resulting in a 31 char string):
yourString.Substring(beginIndex,endIndex-beginIndex+1);
Upvotes: 0
Reputation: 9209
If string S
is your 500 char string then you can:
string result = S.Substring(400, 30);
Upvotes: 0
Reputation: 2755
string x = "aaaa";
string part = x.Substring(400,Math.Min(x.Length,430)-400);
Upvotes: 4
Reputation: 13212
Substring() method of a string object will give you this.
string s = "your huge string .... 700 characters later";
string between = s.Substring(400, 30); //start at char 400, take 30 chars
Upvotes: 0
Reputation: 47038
Use the string.Substring()
method.
Like var truncString = longString.Substring(400, 30);
.
Note, that you should check the length of longString
that it is at least 430 chars. If it is not, Substring
will throw an exception.
Upvotes: 14