-2

I have a String that has 2 whitespaces and i would like to only remove the last space in the String and also remove the last text. components(separatedBy: " ") splits test where there is a space which i don't wanna do.

Current Text

let teamName = "Aston Villa -1" 

I would like it to be like this

teamName = "Aston Villa" 
10
  • @JoakimDanielson -1 Commented May 6, 2020 at 11:48
  • This is coming from the backend, so i just can't remove it like that because the text is normally different. All i want to get is the team name. Thats it. I could just split it and add [0] and [1] together but i don't wanna do it that way Commented May 6, 2020 at 11:51
  • Does this answer your question? Remove last character from string. Swift language Commented May 6, 2020 at 11:51
  • That was just an example Commented May 6, 2020 at 11:52
  • You have to be more specific, what can the last number be. Is it always negative, can it be more than one figure, etc. Commented May 6, 2020 at 11:55

4 Answers 4

2

This is a solution with Regular Expression.

let teamName = "Aston Villa -1" let trimmedTeamName = teamName.replacingOccurrences(of: "(?:\\s[^\\s]+)$", with: "", options: .regularExpression) 

The pattern searches backwards (?:) for a whitespace character (\\s) followed by 1 or more non-whitespace characters ([^\\s]+) at the end of the string ($)


Alternatively you can use range(of with the .backwards option

if let rangeOfLastWhiteSpace = teamName.range(of: " ", options: .backwards) { let trimmedTeamName = String(teamName[..<rangeOfLastWhiteSpace.lowerBound]) } 
Sign up to request clarification or add additional context in comments.

Comments

0

Split the string into the array ["Aston", "Villa", "-1"]. Drop the last element of the array: ["Aston", "Villa"]. Join the array back together "Aston Villa".

let fixedTeamName = teamName.split(separator: " ") .dropLast() .joined(separator: " ") 

Comments

0
let kutcer = "Aston Villa -1" kutcer.lastIndex(of: " ").map( kutcer.prefix(upTo:) ) == "Aston Villa" // true 

…and if you need it as a non-optional String:

kutcer .lastIndex(of: " ") .map( kutcer.prefix(upTo:) ) .map(String.init) ?? kutcer 

Comments

-2

This should work, also for one word team names.

var teamName = "Aston Villa -1" var foundSpace = false while foundSpace == false { if teamName.removeLast() == " " { foundSpace = true } } print(teamName) // "Aston Villa" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.