How to determine the number of specified strings in a string

Asked 2 years ago, Updated 2 years ago, 90 views

Is there a way to find out how many strings are specified in the string search in Swift2?

(Example)
"""Aye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye "There is a string like the one above, and check how many ""kakiku"" are in it

"

Is this possible?I'd like to know how.

Based on Le Pered'OO's response, we implemented it as follows:
Obtain the contents of the src of the img tag from the string (which is the source of the HTML).

let imageHTML: String="<hoge>hugahuga</hoge><img src="payapaya.jpg">p>hunyahunya</p>........"
guard range=imageHTML.rangeOfString("src=") else {return}
let start: Int=imageHTML.startIndex.distanceTo(range.startIndex)
let imageHTML2=(imageHTML as NSSstring).substringFromIndex(start+5)
guard range2 = imageHTML2.rangeOfString("\") else {return}
let start2: Int=imageHTML2.startIndex.distanceTo(range2.startIndex)
let imageURL=(imageHTML2 as NSSstring).substringToIndex(start2)
print(imageURL)//payapaya.jpg

It's a dirty sauce, but I was able to get it just in case.
I would appreciate it if you could let me know if there is a good way to write.

swift swift2

2022-09-30 21:11

2 Answers

As a supplement, I was going to write it in the comment section, but it seems too long to write it in the comment section, so please send it here.

Note that when using the rangeOfString(_:) method of the String class (in the Foundation extension), the result is not the Range<Int> type, but the Optional<Range<CharacterView.Index>.It is common sense for Swift programmers to omit the proper removal of the Optional, but the Range elemental type, the String.CharacterView.Index, should be handled with caution, so I will add a little bit.

let str: String = "Aye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye"
if let range=str.rangeOfString("Right"){
    let start: Int=range.startIndex//->error:cannot convert value of type 'Index' (aka' String.CharacterView.Index') to specified type 'Int'
}

As soon as you try, the value of type String.CharacterView.Index cannot be substituted for type Int variable.

You can't add or subtract from the Int type, and the integer value displayed in print is just the same as the value used as an internal expression (this is a problem), so don't think it really represents the number of characters.

let str2 = "Aye-oh\u{1f48c} kakikakeko"
if let range=str2.rangeOfString("Ready"){
    let start = range.startIndex
    print(start)//->7 (If it starts with 0, it should be 6 by "Number of Characters")
}

The questioner's description alone does not say how to use the value after "checking the number", but if you want to take it out as an integer value, you need to write it in this way.

 if let range=str.rangeOfString("Right"){
    letter —Int=str.startIndex.distanceTo(range.startIndex)
    print(nth)//->5
}
if let range=str2.rangeOfString("Ready"){
    letter —Int=str2.startIndex.distanceTo(range.startIndex)
    print(nth)//->6
}

Now, I've written how to get the number of characters as the Int type, but if I do, I can't use it for String subscripts (accessed by []).

Therefore, when you think about the position and number of characters in a string in Swift, you have to be aware of what unit (Character, unicodeScalar, utf16, utf8) you want and what data type you want (for what purpose later).Please be careful.

(About the additional part)

  • NSSstring substring...The location and length to pass to the system method must be counted in utf16.The code example I gave you counts in Swift.Character units, so depending on the characters that appear, it may malfunction.
  • The Foundation extension of the String class has a method to receive the String.CharacterView.Index type (or its Range type), so you don't have to convert it to Int type, and you don't have to worry about malfunctioning in Swift.Character or utf16 units.

So if you rewrite your code based on that point, it will look like this

let imageHTML: String="<hoge>hugahuga</hoge><img src=\"payapaya.jpg\">p>hunyahunya</p>........"
guard range=imageHTML.rangeOfString("src=") else {return}
let start = range.startIndex.advancedBy(5)
guard range2 = imageHTML.rangeOfString("\",range:start..<imageHTML.endIndex) else {return}
let start2 = range2.startIndex
let imageURL = imageHTML.substringWithRange (start..<start2)
print(imageURL)//payapaya.jpg

However, if you want to extract a part of a particular string that matches the pattern as shown in the example, you may want to use a regular expression.

let imageHTML: String="<hoge>hugahuga</hoge><img src=\"payapaya.jpg\">p>hunyahunya</p>........"
let regex=try!NSRegularExpression( pattern: "src=\"([^\"]*)\", options:[ ])
iflet match=regex.firstMatchInString(imageHTML, options:[], range:NSRange(0..<imageHTML.utf16.count)){
    let imageURL=(imageHTML as NSSstring).substringWithRange(match.rangeAtIndex(1)))
    print (imageURL)
}

As for regular expressions, it is very different from the original questions, so if you have any questions you don't understand after trying, you should ask them again.

Since Yuki Inoue has commented on this, I will put up the Swift 4 version of the above two codes.Both Swift3 and Swift4 have modified their handling of strings.

range(of:) method (formerly rangeOfString(_:))

let imageHTML: String="<hoge>hugahuga</hoge><img src=\"payapaya.jpg\">p>hunyahunya</p>........"
guard range=imageHTML.range(of:"src=") else {return}
// Swift3 and later use the original string method to add and subtract string indexes and integer values
let start = imageHTML.index(range.lowerBound, offsetBy:5)
guard range2 = imageHTML.range(of:"\", range:start..<imageHTML.endIndex) else {return}
let start2 = range2.lowerBound
// Use subscript syntax to obtain a partial string in Swift 4.In this case, `imageURLSubstr` is not `String` type, but `Substring` type.
let imageURLSubstr = imageHTML [start..<start2]
print(imageURLSubstr, type(of:imageURLSubstr))//->payapaya.jpgSubstring
// Use initializer syntax if you want to convert `Substring` to `String`
let imageURLStr=String (imageURLSubstr)
print(imageURLStr, type(of:imageURLStr))//->payapaya.jpg String

Regular expressions

let imageHTML: String="<hoge>hugahuga</hoge><img src=\"payapaya.jpg\">p>hunyahunya</p>........"
let regex=try!NSRegularExpression( pattern: "src=\"([^\"]*)\"")
iflet match=regex.firstMatch(in:imageHTML, options:[], range:NSRange(0..<imageHTML.utf16.count)){
    // How to convert UTF-16-based NSRange to Swift's Range <String.Index> on Swift 4
    US>letrange=Range(match.range(at:1), in:imageHTML)!
    let imageURLSubstr= imageHTML [range]
    print(imageURLSubstr, type(of:imageURLSubstr))//->payapaya.jpgSubstring
    let imageURLStr=String (imageURLSubstr)
    print(imageURLStr, type(of:imageURLStr))//->payapaya.jpg String
}


2022-09-30 21:11

let str = "Aye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye-ye"
letrange=str.rangeOfString("Ready")
print(range)//5..<8

This is possible with the String class rangeOfString method.


2022-09-30 21:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.