Swift - iOS: Remove spaces inside a String before or after any special character The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceHow to remove whitespaces in strings in Swift?Removing All special character except + - operator from NSStringFinding index of character in Swift StringGet nth character of a string in Swift programming languageRemove last character from string. Swift languageAny way to replace characters on Swift String?Swift - iOS 8 - NSKernAttributeName character spacing problemsRemove characters before dotWhy are emoji characters like ๐ฉ๐ฉ๐ง๐ฆ treated so strangely in Swift strings?Regex for string comparison with and without special charactersHow to convert characters of a string “One” into an Integer “1” in swift
Didn't get enough time to take a Coding Test - what to do now?
What's the point in a preamp?
How to delete random line from file using Unix command?
What do you call a plan that's an alternative plan in case your initial plan fails?
University's motivation for having tenure-track positions
What are these Gizmos at Izaña Atmospheric Research Center in Spain?
Is there a writing software that you can sort scenes like slides in PowerPoint?
Am I ethically obligated to go into work on an off day if the reason is sudden?
A pet rabbit called Belle
How is simplicity better than precision and clarity in prose?
Mortgage adviser recommends a longer term than necessary combined with overpayments
Short and long uuids under /dev/disk/by-uuid
Why can't devices on different VLANs, but on the same subnet, communicate?
Was credit for the black hole image misattributed?
How can I protect witches in combat who wear limited clothing?
"... to apply for a visa" or "... and applied for a visa"?
Scientific Reports - Significant Figures
Why can't wing-mounted spoilers be used to steepen approaches?
Match Roman Numerals
Hopping to infinity along a string of digits
ELI5: Why do they say that Israel would have been the fourth country to land a spacecraft on the Moon and why do they call it low cost?
Who or what is the being for whom Being is a question for Heidegger?
What can I do if neighbor is blocking my solar panels intentionally?
What aspect of planet Earth must be changed to prevent the industrial revolution?
Swift - iOS: Remove spaces inside a String before or after any special character
The 2019 Stack Overflow Developer Survey Results Are In
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceHow to remove whitespaces in strings in Swift?Removing All special character except + - operator from NSStringFinding index of character in Swift StringGet nth character of a string in Swift programming languageRemove last character from string. Swift languageAny way to replace characters on Swift String?Swift - iOS 8 - NSKernAttributeName character spacing problemsRemove characters before dotWhy are emoji characters like 👩👩👧👦 treated so strangely in Swift strings?Regex for string comparison with and without special charactersHow to convert characters of a string “One” into an Integer “1” in swift
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I have to do validation to check user entered answer to an application. I want to remove spaces (if any) left or before for bellow special characters.
/
,
:
;
- -
- .
So the final output should be like this.
Ex:
Correct answer => a/b
Answers need to accept => ' a/b ', 'a/ b', 'a /b', 'a/ b ', 'a/b '
I can do this using replacingOccurrences function by replacing all possible values. Is there any better solution for this?
ios swift
|
show 1 more comment
I have to do validation to check user entered answer to an application. I want to remove spaces (if any) left or before for bellow special characters.
/
,
:
;
- -
- .
So the final output should be like this.
Ex:
Correct answer => a/b
Answers need to accept => ' a/b ', 'a/ b', 'a /b', 'a/ b ', 'a/b '
I can do this using replacingOccurrences function by replacing all possible values. Is there any better solution for this?
ios swift
can you show some sample inputs
– Anbu.Karthik
Mar 22 at 4:26
Ex: ' apple / orange', 'apple /orange ', 'apple / orange ', ' apple / orange', => These values need to convert to 'apple/orange'
– sameera
Mar 22 at 4:30
Possible duplicate of How to remove whitespaces in strings in Swift?
– Rakesha Shastri
Mar 22 at 4:38
show your tried code
– Anbu.Karthik
Mar 22 at 4:39
@RakeshaShastri I don't want to trim the string. I need to remove spaces on or before above mentioned special characters (Inside a string).
– sameera
Mar 22 at 4:41
|
show 1 more comment
I have to do validation to check user entered answer to an application. I want to remove spaces (if any) left or before for bellow special characters.
/
,
:
;
- -
- .
So the final output should be like this.
Ex:
Correct answer => a/b
Answers need to accept => ' a/b ', 'a/ b', 'a /b', 'a/ b ', 'a/b '
I can do this using replacingOccurrences function by replacing all possible values. Is there any better solution for this?
ios swift
I have to do validation to check user entered answer to an application. I want to remove spaces (if any) left or before for bellow special characters.
/
,
:
;
- -
- .
So the final output should be like this.
Ex:
Correct answer => a/b
Answers need to accept => ' a/b ', 'a/ b', 'a /b', 'a/ b ', 'a/b '
I can do this using replacingOccurrences function by replacing all possible values. Is there any better solution for this?
ios swift
ios swift
edited Mar 22 at 5:34
sameera
asked Mar 22 at 4:24
sameerasameera
134
134
can you show some sample inputs
– Anbu.Karthik
Mar 22 at 4:26
Ex: ' apple / orange', 'apple /orange ', 'apple / orange ', ' apple / orange', => These values need to convert to 'apple/orange'
– sameera
Mar 22 at 4:30
Possible duplicate of How to remove whitespaces in strings in Swift?
– Rakesha Shastri
Mar 22 at 4:38
show your tried code
– Anbu.Karthik
Mar 22 at 4:39
@RakeshaShastri I don't want to trim the string. I need to remove spaces on or before above mentioned special characters (Inside a string).
– sameera
Mar 22 at 4:41
|
show 1 more comment
can you show some sample inputs
– Anbu.Karthik
Mar 22 at 4:26
Ex: ' apple / orange', 'apple /orange ', 'apple / orange ', ' apple / orange', => These values need to convert to 'apple/orange'
– sameera
Mar 22 at 4:30
Possible duplicate of How to remove whitespaces in strings in Swift?
– Rakesha Shastri
Mar 22 at 4:38
show your tried code
– Anbu.Karthik
Mar 22 at 4:39
@RakeshaShastri I don't want to trim the string. I need to remove spaces on or before above mentioned special characters (Inside a string).
– sameera
Mar 22 at 4:41
can you show some sample inputs
– Anbu.Karthik
Mar 22 at 4:26
can you show some sample inputs
– Anbu.Karthik
Mar 22 at 4:26
Ex: ' apple / orange', 'apple /orange ', 'apple / orange ', ' apple / orange', => These values need to convert to 'apple/orange'
– sameera
Mar 22 at 4:30
Ex: ' apple / orange', 'apple /orange ', 'apple / orange ', ' apple / orange', => These values need to convert to 'apple/orange'
– sameera
Mar 22 at 4:30
Possible duplicate of How to remove whitespaces in strings in Swift?
– Rakesha Shastri
Mar 22 at 4:38
Possible duplicate of How to remove whitespaces in strings in Swift?
– Rakesha Shastri
Mar 22 at 4:38
show your tried code
– Anbu.Karthik
Mar 22 at 4:39
show your tried code
– Anbu.Karthik
Mar 22 at 4:39
@RakeshaShastri I don't want to trim the string. I need to remove spaces on or before above mentioned special characters (Inside a string).
– sameera
Mar 22 at 4:41
@RakeshaShastri I don't want to trim the string. I need to remove spaces on or before above mentioned special characters (Inside a string).
– sameera
Mar 22 at 4:41
|
show 1 more comment
3 Answers
3
active
oldest
votes
You can using regular expression for replace the string with format [ ]+special_char and special_char[ ]+.
Edit
Update "." to "\."
Thanks ielyamani
For example
func acceptedAnswer(of answer: String) -> String
let specialChars = ["/", ":", ",", ";", "-", "\."]
var newAnswer = answer.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars
let beforeCharRegex = "[ ]+" + specialChar
let afterCharRegex = specialChar + "[ ]+"
newAnswer = newAnswer.replacingOccurrences(of: beforeCharRegex, with: specialChar, options: .regularExpression, range: nil)
newAnswer = newAnswer.replacingOccurrences(of: afterCharRegex, with: specialChar, options: .regularExpression, range: nil)
return newAnswer
print(acceptedAnswer(of: " apple / orange : banana "))
// apple/orange:banana
1
I checked your answer. But if there any space between words this solution will not work. Ex: " Apple / Green orange" => Answer should be "Apple/Green orange" - But in your solution answer will be "Apple/Orance.anana"
– sameera
Mar 22 at 5:46
@sameera Use"\."instead of"."
– ielyamani
Mar 22 at 5:46
2
It worked. Thank you for both of you.
– sameera
Mar 22 at 5:52
@ielyamani thank you, I fixed it.
– Quoc Nguyen
Mar 22 at 8:57
@sameera Sorry about it, updated answer with suggestion from ielyamani
– Quoc Nguyen
Mar 22 at 8:58
add a comment |
Remove before and after space of Special character using Range -
let specialChars = ["/",":", ",", ";", "-", "."]
let aString = " AB / CD EF ; G : H , MN O - P"
var trimmedString = aString.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars
if let beforeSpacerange = trimmedString.range(of: " (specialChar)")
trimmedString.replaceSubrange(beforeSpacerange, with: specialChar)
if let afterSpacerange = trimmedString.range(of: "(specialChar) ")
trimmedString.replaceSubrange(afterSpacerange, with: specialChar)
debugPrint(trimmedString)
Hope it will help you. Let me know if you are still having any issue.
Happy coding.
I checked your answer, But I don't need to replace all spaces inside the string. I need to replace spaces which are after or before above special characters. Ex: " Apple / Orance Banana" => "Apple/Orance Banana"
– sameera
Mar 22 at 5:41
You need to read the question again since you have clearly misunderstood it. Not all spaces should be removed, please improve your answer.
– Joakim Danielson
Mar 22 at 6:53
My bad I got that wrong. @JoakimDanielson I've updated my answer. Please check.
– Amir Khan
Mar 22 at 8:53
2
This answer is more optimised than accepted answer. Cheers!
– Manish Bisht
Mar 22 at 11:14
add a comment |
You can use replacingOccurrences which would replace your symbol with whitespaces with just this symbol. For this purpose you can use recursive method
func removed(in text: String) -> String
let symbols = ["/", ",", ":", ";", "-", "."]
var newText = text
symbols.forEach newText = replaced(in: newText, for: $0)
return newText
func replaced(in text: String, for symbol: String) -> String
var newText = text
let left = " (symbol)"
newText = newText.replacingOccurrences(of: left, with: symbol)
let right = "(symbol) "
newText = newText.replacingOccurrences(of: right, with: symbol)
return newText != text ? replaced(in: newText, for: symbol) : newText
Usage:
let string = "Apple / Orange Swift . ObjC Moon : Sun USA - UK"
print(removed(in: string))
Apple/Orange Swift.ObjC Moon:Sun USA-UK
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55292890%2fswift-ios-remove-spaces-inside-a-string-before-or-after-any-special-character%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can using regular expression for replace the string with format [ ]+special_char and special_char[ ]+.
Edit
Update "." to "\."
Thanks ielyamani
For example
func acceptedAnswer(of answer: String) -> String
let specialChars = ["/", ":", ",", ";", "-", "\."]
var newAnswer = answer.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars
let beforeCharRegex = "[ ]+" + specialChar
let afterCharRegex = specialChar + "[ ]+"
newAnswer = newAnswer.replacingOccurrences(of: beforeCharRegex, with: specialChar, options: .regularExpression, range: nil)
newAnswer = newAnswer.replacingOccurrences(of: afterCharRegex, with: specialChar, options: .regularExpression, range: nil)
return newAnswer
print(acceptedAnswer(of: " apple / orange : banana "))
// apple/orange:banana
1
I checked your answer. But if there any space between words this solution will not work. Ex: " Apple / Green orange" => Answer should be "Apple/Green orange" - But in your solution answer will be "Apple/Orance.anana"
– sameera
Mar 22 at 5:46
@sameera Use"\."instead of"."
– ielyamani
Mar 22 at 5:46
2
It worked. Thank you for both of you.
– sameera
Mar 22 at 5:52
@ielyamani thank you, I fixed it.
– Quoc Nguyen
Mar 22 at 8:57
@sameera Sorry about it, updated answer with suggestion from ielyamani
– Quoc Nguyen
Mar 22 at 8:58
add a comment |
You can using regular expression for replace the string with format [ ]+special_char and special_char[ ]+.
Edit
Update "." to "\."
Thanks ielyamani
For example
func acceptedAnswer(of answer: String) -> String
let specialChars = ["/", ":", ",", ";", "-", "\."]
var newAnswer = answer.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars
let beforeCharRegex = "[ ]+" + specialChar
let afterCharRegex = specialChar + "[ ]+"
newAnswer = newAnswer.replacingOccurrences(of: beforeCharRegex, with: specialChar, options: .regularExpression, range: nil)
newAnswer = newAnswer.replacingOccurrences(of: afterCharRegex, with: specialChar, options: .regularExpression, range: nil)
return newAnswer
print(acceptedAnswer(of: " apple / orange : banana "))
// apple/orange:banana
1
I checked your answer. But if there any space between words this solution will not work. Ex: " Apple / Green orange" => Answer should be "Apple/Green orange" - But in your solution answer will be "Apple/Orance.anana"
– sameera
Mar 22 at 5:46
@sameera Use"\."instead of"."
– ielyamani
Mar 22 at 5:46
2
It worked. Thank you for both of you.
– sameera
Mar 22 at 5:52
@ielyamani thank you, I fixed it.
– Quoc Nguyen
Mar 22 at 8:57
@sameera Sorry about it, updated answer with suggestion from ielyamani
– Quoc Nguyen
Mar 22 at 8:58
add a comment |
You can using regular expression for replace the string with format [ ]+special_char and special_char[ ]+.
Edit
Update "." to "\."
Thanks ielyamani
For example
func acceptedAnswer(of answer: String) -> String
let specialChars = ["/", ":", ",", ";", "-", "\."]
var newAnswer = answer.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars
let beforeCharRegex = "[ ]+" + specialChar
let afterCharRegex = specialChar + "[ ]+"
newAnswer = newAnswer.replacingOccurrences(of: beforeCharRegex, with: specialChar, options: .regularExpression, range: nil)
newAnswer = newAnswer.replacingOccurrences(of: afterCharRegex, with: specialChar, options: .regularExpression, range: nil)
return newAnswer
print(acceptedAnswer(of: " apple / orange : banana "))
// apple/orange:banana
You can using regular expression for replace the string with format [ ]+special_char and special_char[ ]+.
Edit
Update "." to "\."
Thanks ielyamani
For example
func acceptedAnswer(of answer: String) -> String
let specialChars = ["/", ":", ",", ";", "-", "\."]
var newAnswer = answer.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars
let beforeCharRegex = "[ ]+" + specialChar
let afterCharRegex = specialChar + "[ ]+"
newAnswer = newAnswer.replacingOccurrences(of: beforeCharRegex, with: specialChar, options: .regularExpression, range: nil)
newAnswer = newAnswer.replacingOccurrences(of: afterCharRegex, with: specialChar, options: .regularExpression, range: nil)
return newAnswer
print(acceptedAnswer(of: " apple / orange : banana "))
// apple/orange:banana
edited Mar 22 at 8:57
answered Mar 22 at 4:51
Quoc NguyenQuoc Nguyen
1,87951521
1,87951521
1
I checked your answer. But if there any space between words this solution will not work. Ex: " Apple / Green orange" => Answer should be "Apple/Green orange" - But in your solution answer will be "Apple/Orance.anana"
– sameera
Mar 22 at 5:46
@sameera Use"\."instead of"."
– ielyamani
Mar 22 at 5:46
2
It worked. Thank you for both of you.
– sameera
Mar 22 at 5:52
@ielyamani thank you, I fixed it.
– Quoc Nguyen
Mar 22 at 8:57
@sameera Sorry about it, updated answer with suggestion from ielyamani
– Quoc Nguyen
Mar 22 at 8:58
add a comment |
1
I checked your answer. But if there any space between words this solution will not work. Ex: " Apple / Green orange" => Answer should be "Apple/Green orange" - But in your solution answer will be "Apple/Orance.anana"
– sameera
Mar 22 at 5:46
@sameera Use"\."instead of"."
– ielyamani
Mar 22 at 5:46
2
It worked. Thank you for both of you.
– sameera
Mar 22 at 5:52
@ielyamani thank you, I fixed it.
– Quoc Nguyen
Mar 22 at 8:57
@sameera Sorry about it, updated answer with suggestion from ielyamani
– Quoc Nguyen
Mar 22 at 8:58
1
1
I checked your answer. But if there any space between words this solution will not work. Ex: " Apple / Green orange" => Answer should be "Apple/Green orange" - But in your solution answer will be "Apple/Orance.anana"
– sameera
Mar 22 at 5:46
I checked your answer. But if there any space between words this solution will not work. Ex: " Apple / Green orange" => Answer should be "Apple/Green orange" - But in your solution answer will be "Apple/Orance.anana"
– sameera
Mar 22 at 5:46
@sameera Use
"\." instead of "."– ielyamani
Mar 22 at 5:46
@sameera Use
"\." instead of "."– ielyamani
Mar 22 at 5:46
2
2
It worked. Thank you for both of you.
– sameera
Mar 22 at 5:52
It worked. Thank you for both of you.
– sameera
Mar 22 at 5:52
@ielyamani thank you, I fixed it.
– Quoc Nguyen
Mar 22 at 8:57
@ielyamani thank you, I fixed it.
– Quoc Nguyen
Mar 22 at 8:57
@sameera Sorry about it, updated answer with suggestion from ielyamani
– Quoc Nguyen
Mar 22 at 8:58
@sameera Sorry about it, updated answer with suggestion from ielyamani
– Quoc Nguyen
Mar 22 at 8:58
add a comment |
Remove before and after space of Special character using Range -
let specialChars = ["/",":", ",", ";", "-", "."]
let aString = " AB / CD EF ; G : H , MN O - P"
var trimmedString = aString.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars
if let beforeSpacerange = trimmedString.range(of: " (specialChar)")
trimmedString.replaceSubrange(beforeSpacerange, with: specialChar)
if let afterSpacerange = trimmedString.range(of: "(specialChar) ")
trimmedString.replaceSubrange(afterSpacerange, with: specialChar)
debugPrint(trimmedString)
Hope it will help you. Let me know if you are still having any issue.
Happy coding.
I checked your answer, But I don't need to replace all spaces inside the string. I need to replace spaces which are after or before above special characters. Ex: " Apple / Orance Banana" => "Apple/Orance Banana"
– sameera
Mar 22 at 5:41
You need to read the question again since you have clearly misunderstood it. Not all spaces should be removed, please improve your answer.
– Joakim Danielson
Mar 22 at 6:53
My bad I got that wrong. @JoakimDanielson I've updated my answer. Please check.
– Amir Khan
Mar 22 at 8:53
2
This answer is more optimised than accepted answer. Cheers!
– Manish Bisht
Mar 22 at 11:14
add a comment |
Remove before and after space of Special character using Range -
let specialChars = ["/",":", ",", ";", "-", "."]
let aString = " AB / CD EF ; G : H , MN O - P"
var trimmedString = aString.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars
if let beforeSpacerange = trimmedString.range(of: " (specialChar)")
trimmedString.replaceSubrange(beforeSpacerange, with: specialChar)
if let afterSpacerange = trimmedString.range(of: "(specialChar) ")
trimmedString.replaceSubrange(afterSpacerange, with: specialChar)
debugPrint(trimmedString)
Hope it will help you. Let me know if you are still having any issue.
Happy coding.
I checked your answer, But I don't need to replace all spaces inside the string. I need to replace spaces which are after or before above special characters. Ex: " Apple / Orance Banana" => "Apple/Orance Banana"
– sameera
Mar 22 at 5:41
You need to read the question again since you have clearly misunderstood it. Not all spaces should be removed, please improve your answer.
– Joakim Danielson
Mar 22 at 6:53
My bad I got that wrong. @JoakimDanielson I've updated my answer. Please check.
– Amir Khan
Mar 22 at 8:53
2
This answer is more optimised than accepted answer. Cheers!
– Manish Bisht
Mar 22 at 11:14
add a comment |
Remove before and after space of Special character using Range -
let specialChars = ["/",":", ",", ";", "-", "."]
let aString = " AB / CD EF ; G : H , MN O - P"
var trimmedString = aString.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars
if let beforeSpacerange = trimmedString.range(of: " (specialChar)")
trimmedString.replaceSubrange(beforeSpacerange, with: specialChar)
if let afterSpacerange = trimmedString.range(of: "(specialChar) ")
trimmedString.replaceSubrange(afterSpacerange, with: specialChar)
debugPrint(trimmedString)
Hope it will help you. Let me know if you are still having any issue.
Happy coding.
Remove before and after space of Special character using Range -
let specialChars = ["/",":", ",", ";", "-", "."]
let aString = " AB / CD EF ; G : H , MN O - P"
var trimmedString = aString.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars
if let beforeSpacerange = trimmedString.range(of: " (specialChar)")
trimmedString.replaceSubrange(beforeSpacerange, with: specialChar)
if let afterSpacerange = trimmedString.range(of: "(specialChar) ")
trimmedString.replaceSubrange(afterSpacerange, with: specialChar)
debugPrint(trimmedString)
Hope it will help you. Let me know if you are still having any issue.
Happy coding.
edited Mar 22 at 8:52
answered Mar 22 at 4:51
Amir KhanAmir Khan
1,8541726
1,8541726
I checked your answer, But I don't need to replace all spaces inside the string. I need to replace spaces which are after or before above special characters. Ex: " Apple / Orance Banana" => "Apple/Orance Banana"
– sameera
Mar 22 at 5:41
You need to read the question again since you have clearly misunderstood it. Not all spaces should be removed, please improve your answer.
– Joakim Danielson
Mar 22 at 6:53
My bad I got that wrong. @JoakimDanielson I've updated my answer. Please check.
– Amir Khan
Mar 22 at 8:53
2
This answer is more optimised than accepted answer. Cheers!
– Manish Bisht
Mar 22 at 11:14
add a comment |
I checked your answer, But I don't need to replace all spaces inside the string. I need to replace spaces which are after or before above special characters. Ex: " Apple / Orance Banana" => "Apple/Orance Banana"
– sameera
Mar 22 at 5:41
You need to read the question again since you have clearly misunderstood it. Not all spaces should be removed, please improve your answer.
– Joakim Danielson
Mar 22 at 6:53
My bad I got that wrong. @JoakimDanielson I've updated my answer. Please check.
– Amir Khan
Mar 22 at 8:53
2
This answer is more optimised than accepted answer. Cheers!
– Manish Bisht
Mar 22 at 11:14
I checked your answer, But I don't need to replace all spaces inside the string. I need to replace spaces which are after or before above special characters. Ex: " Apple / Orance Banana" => "Apple/Orance Banana"
– sameera
Mar 22 at 5:41
I checked your answer, But I don't need to replace all spaces inside the string. I need to replace spaces which are after or before above special characters. Ex: " Apple / Orance Banana" => "Apple/Orance Banana"
– sameera
Mar 22 at 5:41
You need to read the question again since you have clearly misunderstood it. Not all spaces should be removed, please improve your answer.
– Joakim Danielson
Mar 22 at 6:53
You need to read the question again since you have clearly misunderstood it. Not all spaces should be removed, please improve your answer.
– Joakim Danielson
Mar 22 at 6:53
My bad I got that wrong. @JoakimDanielson I've updated my answer. Please check.
– Amir Khan
Mar 22 at 8:53
My bad I got that wrong. @JoakimDanielson I've updated my answer. Please check.
– Amir Khan
Mar 22 at 8:53
2
2
This answer is more optimised than accepted answer. Cheers!
– Manish Bisht
Mar 22 at 11:14
This answer is more optimised than accepted answer. Cheers!
– Manish Bisht
Mar 22 at 11:14
add a comment |
You can use replacingOccurrences which would replace your symbol with whitespaces with just this symbol. For this purpose you can use recursive method
func removed(in text: String) -> String
let symbols = ["/", ",", ":", ";", "-", "."]
var newText = text
symbols.forEach newText = replaced(in: newText, for: $0)
return newText
func replaced(in text: String, for symbol: String) -> String
var newText = text
let left = " (symbol)"
newText = newText.replacingOccurrences(of: left, with: symbol)
let right = "(symbol) "
newText = newText.replacingOccurrences(of: right, with: symbol)
return newText != text ? replaced(in: newText, for: symbol) : newText
Usage:
let string = "Apple / Orange Swift . ObjC Moon : Sun USA - UK"
print(removed(in: string))
Apple/Orange Swift.ObjC Moon:Sun USA-UK
add a comment |
You can use replacingOccurrences which would replace your symbol with whitespaces with just this symbol. For this purpose you can use recursive method
func removed(in text: String) -> String
let symbols = ["/", ",", ":", ";", "-", "."]
var newText = text
symbols.forEach newText = replaced(in: newText, for: $0)
return newText
func replaced(in text: String, for symbol: String) -> String
var newText = text
let left = " (symbol)"
newText = newText.replacingOccurrences(of: left, with: symbol)
let right = "(symbol) "
newText = newText.replacingOccurrences(of: right, with: symbol)
return newText != text ? replaced(in: newText, for: symbol) : newText
Usage:
let string = "Apple / Orange Swift . ObjC Moon : Sun USA - UK"
print(removed(in: string))
Apple/Orange Swift.ObjC Moon:Sun USA-UK
add a comment |
You can use replacingOccurrences which would replace your symbol with whitespaces with just this symbol. For this purpose you can use recursive method
func removed(in text: String) -> String
let symbols = ["/", ",", ":", ";", "-", "."]
var newText = text
symbols.forEach newText = replaced(in: newText, for: $0)
return newText
func replaced(in text: String, for symbol: String) -> String
var newText = text
let left = " (symbol)"
newText = newText.replacingOccurrences(of: left, with: symbol)
let right = "(symbol) "
newText = newText.replacingOccurrences(of: right, with: symbol)
return newText != text ? replaced(in: newText, for: symbol) : newText
Usage:
let string = "Apple / Orange Swift . ObjC Moon : Sun USA - UK"
print(removed(in: string))
Apple/Orange Swift.ObjC Moon:Sun USA-UK
You can use replacingOccurrences which would replace your symbol with whitespaces with just this symbol. For this purpose you can use recursive method
func removed(in text: String) -> String
let symbols = ["/", ",", ":", ";", "-", "."]
var newText = text
symbols.forEach newText = replaced(in: newText, for: $0)
return newText
func replaced(in text: String, for symbol: String) -> String
var newText = text
let left = " (symbol)"
newText = newText.replacingOccurrences(of: left, with: symbol)
let right = "(symbol) "
newText = newText.replacingOccurrences(of: right, with: symbol)
return newText != text ? replaced(in: newText, for: symbol) : newText
Usage:
let string = "Apple / Orange Swift . ObjC Moon : Sun USA - UK"
print(removed(in: string))
Apple/Orange Swift.ObjC Moon:Sun USA-UK
edited Mar 22 at 6:35
answered Mar 22 at 6:14
Robert DreslerRobert Dresler
8,1222727
8,1222727
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55292890%2fswift-ios-remove-spaces-inside-a-string-before-or-after-any-special-character%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
can you show some sample inputs
– Anbu.Karthik
Mar 22 at 4:26
Ex: ' apple / orange', 'apple /orange ', 'apple / orange ', ' apple / orange', => These values need to convert to 'apple/orange'
– sameera
Mar 22 at 4:30
Possible duplicate of How to remove whitespaces in strings in Swift?
– Rakesha Shastri
Mar 22 at 4:38
show your tried code
– Anbu.Karthik
Mar 22 at 4:39
@RakeshaShastri I don't want to trim the string. I need to remove spaces on or before above mentioned special characters (Inside a string).
– sameera
Mar 22 at 4:41