VYT
VYT

Reputation: 1071

Generation of an array of substring from a string in swift

I have a problem with generation of an array of substrings from a string in the following code

var primers=[String]()

var lengthOfPrimer = 20

var  lentghOfText = str1.characters.count

var rest = lentghOfText - lengthOfPrimer

for var i = 0; i <= str1.characters.count; ++i
{

var temp = rest - i

var substring1 = str1.substringWithRange(Range<String.Index>(start: advance(str1.startIndex, i), end: advance(str1.endIndex, -temp)))

primers.append(substring1)

}

In playground I have the following error at the line with the substring1 code – Execution was interrupted: reason: EXC_BAD_INSTRUCTION (code=EXC 1386_INVOP, subcode=0x0. In spite of error sign, I can see in playground the generated set of substrings in loop, but when I tried to use this code in program this code also did not work, What is wrong? What should I do?

Upvotes: 0

Views: 125

Answers (2)

jtbandes
jtbandes

Reputation: 118691

Your error is coming from trying to advance the endIndex.

But how about something a little simpler? (Swift 2)

var first = str1.startIndex
var last = advance(first, 20 - 1, str1.endIndex)

while last != str1.endIndex {
    primers.append(str1[first++ ... last++])
}

print("\n".join(primers))

// output:
// ACAAGATGCCATTGTCCCCC
// CAAGATGCCATTGTCCCCCG
// AAGATGCCATTGTCCCCCGG
// AGATGCCATTGTCCCCCGGC
// GATGCCATTGTCCCCCGGCC
// ATGCCATTGTCCCCCGGCCT
// TGCCATTGTCCCCCGGCCTC
// GCCATTGTCCCCCGGCCTCC
// CCATTGTCCCCCGGCCTCCT
// CATTGTCCCCCGGCCTCCTG
// ATTGTCCCCCGGCCTCCTGC
// TTGTCCCCCGGCCTCCTGCT
// ...

Or the for loop way:

for var first = str1.startIndex, last = advance(first, 20 - 1, str1.endIndex);
    last != str1.endIndex;
    ++first, ++last
{
    primers.append(str1[first...last])
}

Upvotes: 2

w0mbat
w0mbat

Reputation: 2459

for var i = 0; i <= str1.characters.count; ++i

Without getting into the rest of this code, this for loop is wrong. You are reading past the end of the string because you are using <= when you should be using <.

Also you are calling str1.characters.count in the loop even though you have that value in a variable, which is slow.

Try:

for var i = 0; i < lengthOfText; ++i

Upvotes: 2

Related Questions