user9969
user9969

Reputation: 16040

String Manipulation.Find string between 2 indexes

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

Answers (8)

lastlink
lastlink

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

cs_student_007
cs_student_007

Reputation: 21

string result = S.Substring(startIndex, startIndex - endIndex);

Upvotes: 2

YenForYang
YenForYang

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

ChrisBD
ChrisBD

Reputation: 9209

If string S is your 500 char string then you can:

string result = S.Substring(400, 30);

Upvotes: 0

Adilson de Almeida Jr
Adilson de Almeida Jr

Reputation: 2755

string x = "aaaa";
string part = x.Substring(400,Math.Min(x.Length,430)-400);

Upvotes: 4

MattW
MattW

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

Blau
Blau

Reputation: 5762

yourstring.Substring(startindex, length)

Upvotes: 0

Albin Sunnanbo
Albin Sunnanbo

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

Related Questions