Spaces in string causing fatal error: cannot increment beyond endIndex - string

I have a string "PIXEL STUDIOS - TEST1" My code works until I reach the first space in the string.
var str = label.stringValue
let c = str.characters
let r = c.index(c.startIndex, offsetBy: 6)..<c.index(c.endIndex, offsetBy: 0)
let substring = str[r]
print(substring)
When I run my code and offsetBy 5 it works but when I try to offset past that point I get the error. Is there something else I need to do to handle spaces in my string?

Your code is working with the given string:
var str = "PIXEL STUDIOS - TEST1"
let c = str.characters
let r = c.index(c.startIndex, offsetBy: 6)..<c.index(c.endIndex, offsetBy: 0)
let substring = str[r]
print(substring)
prints:
STUDIOS - TEST1
Conclusion: label.stringValue is fishy.
Print it out for further investigations.

Related

Have to count a character occurrence in Nim string type

How to count a character occurrence in string in Nim, mainly using its native statements prior go to module ? eg.
var
str = "Hello World"
c : int
c = numChar( "o", str ) # <- illustration only ?
The earlier answer is correct but if you do not want to import any modules you can write your own procedure:
proc count_char(value: string = "Hello World", ch: char = 'o'): int =
var cnt_c: int = 0
for c in value:
if c == ch:
cnt_c += 1
result = cnt_c
var
val: string = "Mother Goose"
ch: char = 'o'
echo $count_char(val, ch)
PS: Unrelated - Need syntax highlight for nim-lang on SO.
Use the count function from strutils:
import std/strutils
let str = "Hello World"
let count = count(str, 'o')
assert count = 1
There’s also a string overload for counting sub strings as well.

In Swift NSAttributedString has more characters than String?

I am trying to add attributes to some ranges in Swift String.
I found ranges of first and last symbol in substring and color the text between them (including) in red.
let mutableString = NSMutableAttributedString(string: text)
let str = mutableString.string
//Red symbols
var t = 0
let symbols = mutableString.string.characters.count
while t < symbols {
if str[t] == "[" {
let startIndex = t
while str[t] != "]" {
t += 1
}
t += 1
let endIndex = t
mutableString.addAttribute(
NSForegroundColorAttributeName,
value: UIColor.redColor(),
range: NSMakeRange(startIndex, endIndex - startIndex))
}
t += 1
}
But I found that ranges in String and in NSMutableAttributedString are not equal. Range in String is shorter (this text is not in Unicode encoding).
Is there a some way to find ranges not in underlying String but in NSAttributedString to find it correctly?
Example:
print(mutableString.length) //550
print(mutableString.string.characters.count) //548
Why is this difference?
Yes it is possible to find ranges in NSMutableAttributedString.
Example :
let text = "[I love Ukraine!]"
var start = text.rangeOfString("[")
var finish = text.rangeOfString("]")
let mutableString = NSMutableAttributedString(string: text)
let startIndex = mutableString.string.rangeOfString("[")
let finishIndex = mutableString.string.rangeOfString("]")
Example output from playground:
Distinguish between String and NSString, even though they are bridged to one another. String is native Swift, and you define a range in terms of String character index. NSString is Cocoa (Foundation), and you define a range in terms of NSRange.
Yes, I found it.
Windows end-of-line "\r\n" is two symbols in NSAttributedString but only one character in Swift String.
I use checking in my code:
let symbols = mutableString.string.characters.count
var extendedSymbols = 0
while t < symbols {
if str[t] == "\r\n" { extendedSymbols += 1 }
else if str[t] == "[" {
let startIndex = t + extendedSymbols
while str[t] != "]" {
t += 1
}
t += 1
let endIndex = t + extendedSymbols
mutableString.addAttribute(
NSForegroundColorAttributeName,
value: UIColor.redColor(),
range: NSMakeRange(startIndex, endIndex - startIndex))
}
t += 1
}
Thank you all for help!!!

Creating Range<String.Index> from constant Ints

What is wrong with this piece of code for constructing a range that should then serve in a call to substringWithRange?
let range = Range<String.Index>(start: 0, end: 3)
The Swift compiler (in Xcode 7.1.1) marks it with this error message:
Cannot invoke initializer for type 'Range<Index>' with an argument list of type '(start: Int, end: Int)'
You need to reference the startIndex of a specific string, then advance:
let longString = "Supercalifragilistic"
let startIndex = longString.startIndex
let range = Range(start: startIndex, end: startIndex.advancedBy(3))
You can use various ways
let startIndex = text.startIndex
let endIndex = text.endIndex
var range1 = startIndex.advancedBy(1) ..< text.endIndex.advancedBy(-4)
var range2 = startIndex.advancedBy(0) ..< startIndex.advancedBy(5)
var range3 = startIndex ..< endIndex
let substring = text.substringWithRange(range)

Remove nth character from string

I have seen many methods for removing the last character from a string. Is there however a way to remove any old character based on its index?
Here is a safe Swift 4 implementation.
var s = "Hello, I must be going"
var n = 5
if let index = s.index(s.startIndex, offsetBy: n, limitedBy: s.endIndex) {
s.remove(at: index)
print(s) // prints "Hello I must be going"
} else {
print("\(n) is out of range")
}
While string indices aren't random-access and aren't numbers, you can advance them by a number in order to access the nth character:
var s = "Hello, I must be going"
s.removeAtIndex(advance(s.startIndex, 5))
println(s) // prints "Hello I must be going"
Of course, you should always check the string is at least 5 in length before doing this!
edit: as #MartinR points out, you can use the with-end-index version of advance to avoid the risk of running past the end:
let index = advance(s.startIndex, 5, s.endIndex)
if index != s.endIndex { s.removeAtIndex(index) }
As ever, optionals are your friend:
// find returns index of first match,
// as an optional with nil for no match
if let idx = s.characters.index(of:",") {
// this will only be executed if non-nil,
// idx will be the unwrapped result of find
s.removeAtIndex(idx)
}
Swift 3.2
let str = "hello"
let position = 2
let subStr = str.prefix(upTo: str.index(str.startIndex, offsetBy: position)) + str.suffix(from: str.index(str.startIndex, offsetBy: (position + 1)))
print(subStr)
"helo"
var hello = "hello world!"
Let's say we want to remove the "w". (It's at the 6th index position.)
First: Create an Index for that position. (I'm making the return type Index explicit; it's not required).
let index:Index = hello.startIndex.advancedBy(6)
Second: Call removeAtIndex() and pass it our just-made index. (Notice it returns the character in question)
let choppedChar:Character = hello.removeAtIndex(index)
print(hello) // prints hello orld!
print(choppedChar) // prints w

better way to get the last character in a string in f#

I want the last character from a string
I've got str.[str.Length - 1], but that's ugly. There must be a better way.
There's no better way to do it - what you have is fine.
If you really plan to do it a lot, you can author an F# extension property on the string type:
let s = "food"
type System.String with
member this.Last =
this.Chars(this.Length-1) // may raise an exception
printfn "%c" s.Last
This could be also handy:
let s = "I am string"
let lastChar = s |> Seq.last
Result:
val lastChar : char = 'g'
(This is old question), someone might find this useful, orig answer from Brian.
type System.String with
member this.Last() =
if this.Length > 1 then
this.Chars(this.Length - 1).ToString()
else
this.[0].ToString()
member this.Last(n:int) =
let absn = Math.Abs(n)
if this.Length > absn then
let nn =
let a = if absn = 0 then 1 else absn
let b = this.Length - a
if b < 0 then 0 else b
this.Chars(nn).ToString()
else
this.[0].ToString()
"ABCD".Last() -> "D"
"ABCD".Last(1) -> "D"
"ABCD".Last(-1) -> "D"
"ABCD".Last(2) -> "C"
You could also treat it as a sequence, but I'm not sure if that's any more or less ugly than the solution you have:
Seq.nth (Seq.length str - 1) str

Resources