Extract Last Word in String with Swift

Extract Last Word in String with Swift

You can use String method enumerateSubstringsInRange. First parameter just pass your string Range<Index>, and the option .byWords. Just append each substring to the resulting collection and return it.

Swift 5 or later (for older Swift syntax check edit history)

import Foundation

extension StringProtocol { // for Swift 4 you need to add the constrain `where Index == String.Index`
var byWords: [SubSequence] {
var byWords: [SubSequence] = []
enumerateSubstrings(in: startIndex..., options: .byWords) { _, range, _, _ in
byWords.append(self[range])
}
return byWords
}
}

Usage:

let sentence = "Out of this world!!!"
let words = sentence.byWords // ["Out", "of", "this", "world"]
let firstWord = words.first // "Out"
let lastWord = words.last // world"
let first2Words = words.prefix(2) // ["Out", "of"]
let last2Words = words.suffix(2) // ["this", "world"]

Without import Foundation

Cleaning punctuation characters filtering the letters and spaces of the string

let clean = sentence.filter{ $0.isLetter || $0.isWhitespace }

find the index after the index of the last space in a string

if let lastIndex = clean.lastIndex(of: " "), let index = clean.index(lastIndex, offsetBy: 1, limitedBy: clean.index(before: clean.endIndex)) {
let lastWord = clean[index...]
print(lastWord) // "world"
}

find the index of the first space in a string

if let index = clean.firstIndex(of: " ") {
let firstWord = clean[...index]
print(firstWord) // "Out""
}

Efficiently remove the last word from a string in Swift

1.

One thing, iteration isn't necessary for this:

for word in words {
arrayOfWords += [word]
}

You can just do:

arrayOfWords += words

2.

Breaking the for loop will prevent iterating unnecessarily:

for (mistake, word) in autocorrectList {
println("The mistake is \(mistake)")
if mistake == arrayOfWords.last {
fullString = word
hasWordReadyToCorrect = true
break; // Add this to stop iterating through 'autocorrectList'
}
}

Or even better, forget the for-loop completely:

if let word = autocorrectList[arrayOfWords.last] {
fullString = word
hasWordReadyToCorrect = true
}

Ultimately what you're doing is seeing if the last word of the entered text matches any of the keys in the autocorrect list. You can just try to get the value directly using optional binding like this.

---

I'll let you know if I think of more.

Get the last word that is being typed

Try with below code, its working at my end.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let nsString = textView.text as NSString?
let newString = nsString?.replacingCharacters(in: range, with: text)
let arr = newString?.components(separatedBy: " ")
self.lblWord.text = arr?.last
return true
}

Getting the last word of an NSString

If you want to be super-robust:

__block NSString *lastWord = nil;

[someNSStringHere enumerateSubstringsInRange:NSMakeRange(0, [someNSStringHere length]) options:NSStringEnumerationByWords | NSStringEnumerationReverse usingBlock:^(NSString *substring, NSRange subrange, NSRange enclosingRange, BOOL *stop) {
lastWord = substring;
*stop = YES;
}];

(This should also work with non-Roman languages; iOS 4+/OS X 10.6+.)

Basic explanation:

-enumerateSubstringsInRage:options:usingBlock: does what it says on the tin: it enumerates substrings, which are defined by what you pass in as the options. NSStringEnumerationByWords says "I want words given to me", and NSStringEnumerationReverse says "start at the end of the string instead of the beginning".

Since we're starting from the end, the first word given to us in substring will be the last word in the string, so we set lastWord to that, and then set the BOOL pointed to by stop to YES, so the enumeration stops right away.

lastWord is of course defined as __block so we can set it inside the block and see it outside, and it's initialized to nil so if the string has no words (e.g., if it's empty or is all punctuation) we don't crash when we try to use lastWord.

How can I replace the last word using Regex?

I think it's because the * regex operator will

Match 0 or more times. Match as many times as possible.

This might be causing it to also match the 'no characters at the end' in addition to the word at the end, resulting in two replacements.

As mentioned by @Code Different, if you use let pattern = "\\w+$" instead, it will only match if there are characters, eliminating the 'no characters' match.

"Word1 Word2"
^some characters and then end
^0 characters and then end

Swift: Get an index of beginning and ending character of a word in a String

You can call range(of:) on two slices of the given string:
text[..<index] is the text preceding the given character position,
and text[index...] is the text starting at the given position.

Example:

let text = "jim@domain.com, bill@domain.com, chad@domain.com, tom@domain.com"
let index = text.index(text.startIndex, offsetBy: 39)

// Search the space before the given position:
let start = text[..<index].range(of: " ", options: .backwards)?.upperBound ?? text.startIndex

// Search the comma after the given position:
let end = text[index...].range(of: ",")?.lowerBound ?? text.endIndex

print(text[start..<end]) // chad@domain.com

Both range(of:) calls return nil if no space (or comma) has
been found. In that case the nil-coalescing operator ?? is used
to get the start (or end) index instead.

(Note that this works because Substrings share a common index
with their originating string.)


An alternative approach is to use a "data detector",
so that the URL detection does not depend on certain separators.

Example (compare How to detect a URL in a String using NSDataDetector):

let text = "jim@domain.com, bill@domain.com, chad@domain.com, tom@domain.com"
let index = text.index(text.startIndex, offsetBy: 39)

let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: text, range: NSRange(location: 0, length: text.utf16.count))

for match in matches {
if let range = Range(match.range, in: text), range.contains(index) {
print(text[range])
}
}

Swift: How to split a string and then extract specific substring?

There is a solution below, it will extract any string between brackets into an array without brackets, it also gives you string without element as word as an array element:

var myString = "exampleString ( 123 ) "

//creates result array from String by separating elements by space
var result = myString.split(separator: " ")

//filters array to remove '(' and ')'
result = result.filter { $0 != "(" && $0 != ")" }

print(result)

Then if you want to build a String back from result array with string elements, do the following:

var resultString = result.joined(separator: " ")

print(resultString)

Might not be ideal, but it might be useful for you.

Extract a whole word from string In Swift

Split your string into array by space char (" "), and return component that contains your 'av' string.

How to find the last word in a string

String#lastIndexOf and String#substring are your friends here.

chars in Java can be directly converted to ints, which we'll use to find the last space. Then we'll simply substring from there.

String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(phrase.lastIndexOf(' ')));

This prints the space character itself too. To get rid of that, we just increment the index at which we substring by one.

String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(1 + phrase.lastIndexOf(' ')));

If you don't want to use String#lastIndexOf, you can loop through the string and substring it at every space until you don't have any left.

String phrase = "The last word of this sentence is stackoverflow";
String subPhrase = phrase;
while(true) {
String temp = subPhrase.substring(1 + subPhrase.indexOf(" "));
if(temp.equals(subPhrase)) {
break;
} else {
subPhrase = temp;
}
}
System.out.println(subPhrase);


Related Topics



Leave a reply



Submit