What Is the More Elegant Way to Remove All Characters After Specific Character in the String Object in Swift

What is the more elegant way to remove all characters after specific character in the String object in Swift

Here is a way to do it:

var str = "str.str"

if let dotRange = str.rangeOfString(".") {
str.removeRange(dotRange.startIndex..<str.endIndex)
}

Update
In Swift 3 it is:

var str = "str.str"

if let dotRange = str.range(of: ".") {
str.removeSubrange(dotRange.lowerBound..<str.endIndex)
}

Delete all characters after a certain character from a string in Swift

You can use StringProtocol method range(of string:), get the resulting range lowerBound, create a PartialRangeUpTo with it and subscript the original string:

Swift 4 or later

let word = "orange"
if let index = word.range(of: "n")?.lowerBound {
let substring = word[..<index] // "ora"
// or let substring = word.prefix(upTo: index) // "ora"
// (see picture below) Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collection’s subscript.
// The subscript notation is preferred over prefix(upTo:).

let string = String(substring)
print(string) // "ora"
}

Sample Image

Remove characters by position from string

I would just build a new string using prefix and suffix or dropFirst:

let subCadenaTX4 = "25121997"

// Desire: drop characters at position 4 and 5
// use prefix to get the first 4 characters
// use suffix to get the last 2 characters
// call String() to covert the result back to String
let result = String(subCadenaTX4.prefix(4) + subCadenaTX4.suffix(2))

or:

// Desire: drop characters at position 4 and 5
// use prefix to get the first 4 characters
// Use dropFirst(6) to pick string starting at position 6
// call String to convert result to String
let result = String(subCadenaTX4.prefix(4) + subCadenaTX4.dropFirst(6))

What is the most succinct way to remove the first character from a string in Swift?

If you're using Swift 3, you can ignore the second section of this answer. Good news is, this is now actually succinct again! Just using String's new remove(at:) method.

var myString = "Hello, World"
myString.remove(at: myString.startIndex)

myString // "ello, World"

I like the global dropFirst() function for this.

let original = "Hello" // Hello
let sliced = dropFirst(original) // ello

It's short, clear, and works for anything that conforms to the Sliceable protocol.

If you're using Swift 2, this answer has changed. You can still use dropFirst, but not without dropping the first character from your strings characters property and then converting the result back to a String. dropFirst has also become a method, not a function.

let original = "Hello" // Hello
let sliced = String(original.characters.dropFirst()) // ello

Another alternative is to use the suffix function to splice the string's UTF16View. Of course, this has to be converted back to a String afterwards as well.

let original = "Hello" // Hello
let sliced = String(suffix(original.utf16, original.utf16.count - 1)) // ello

All this is to say that the solution I originally provided has turned out not to be the most succinct way of doing this in newer versions of Swift. I recommend falling back on @chris' solution using removeAtIndex() if you're looking for a short and intuitive solution.

var original = "Hello" // Hello
let removedChar = original.removeAtIndex(original.startIndex)

original // ello

And as pointed out by @vacawama in the comments below, another option that doesn't modify the original String is to use substringFromIndex.

let original = "Hello" // Hello
let substring = original.substringFromIndex(advance(original.startIndex, 1)) // ello

Or if you happen to be looking to drop a character off the beginning and end of the String, you can use substringWithRange. Just be sure to guard against the condition when startIndex + n > endIndex - m.

let original = "Hello" // Hello

let newStartIndex = advance(original.startIndex, 1)
let newEndIndex = advance(original.endIndex, -1)

let substring = original.substringWithRange(newStartIndex..<newEndIndex) // ell

The last line can also be written using subscript notation.

let substring = original[newStartIndex..<newEndIndex]

How does String substring work in Swift

Sample Image

All of the following examples use

var str = "Hello, playground"

Swift 4

Strings got a pretty big overhaul in Swift 4. When you get some substring from a String now, you get a Substring type back rather than a String. Why is this? Strings are value types in Swift. That means if you use one String to make a new one, then it has to be copied over. This is good for stability (no one else is going to change it without your knowledge) but bad for efficiency.

A Substring, on the other hand, is a reference back to the original String from which it came. Here is an image from the documentation illustrating that.

No copying is needed so it is much more efficient to use. However, imagine you got a ten character Substring from a million character String. Because the Substring is referencing the String, the system would have to hold on to the entire String for as long as the Substring is around. Thus, whenever you are done manipulating your Substring, convert it to a String.

let myString = String(mySubstring)

This will copy just the substring over and the memory holding old String can be reclaimed. Substrings (as a type) are meant to be short lived.

Another big improvement in Swift 4 is that Strings are Collections (again). That means that whatever you can do to a Collection, you can do to a String (use subscripts, iterate over the characters, filter, etc).

The following examples show how to get a substring in Swift.

Getting substrings

You can get a substring from a string by using subscripts or a number of other methods (for example, prefix, suffix, split). You still need to use String.Index and not an Int index for the range, though. (See my other answer if you need help with that.)

Beginning of a string

You can use a subscript (note the Swift 4 one-sided range):

let index = str.index(str.startIndex, offsetBy: 5)
let mySubstring = str[..<index] // Hello

or prefix:

let index = str.index(str.startIndex, offsetBy: 5)
let mySubstring = str.prefix(upTo: index) // Hello

or even easier:

let mySubstring = str.prefix(5) // Hello

End of a string

Using subscripts:

let index = str.index(str.endIndex, offsetBy: -10)
let mySubstring = str[index...] // playground

or suffix:

let index = str.index(str.endIndex, offsetBy: -10)
let mySubstring = str.suffix(from: index) // playground

or even easier:

let mySubstring = str.suffix(10) // playground

Note that when using the suffix(from: index) I had to count back from the end by using -10. That is not necessary when just using suffix(x), which just takes the last x characters of a String.

Range in a string

Again we simply use subscripts here.

let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end

let mySubstring = str[range] // play

Converting Substring to String

Don't forget, when you are ready to save your substring, you should convert it to a String so that the old string's memory can be cleaned up.

let myString = String(mySubstring)

Using an Int index extension?

I'm hesitant to use an Int based index extension after reading the article Strings in Swift 3 by Airspeed Velocity and Ole Begemann. Although in Swift 4, Strings are collections, the Swift team purposely hasn't used Int indexes. It is still String.Index. This has to do with Swift Characters being composed of varying numbers of Unicode codepoints. The actual index has to be uniquely calculated for every string.

I have to say, I hope the Swift team finds a way to abstract away String.Index in the future. But until then, I am choosing to use their API. It helps me to remember that String manipulations are not just simple Int index lookups.

Does swift have a trim method on String?

Here's how you remove all the whitespace from the beginning and end of a String.

(Example tested with Swift 2.0.)

let myString = "  \t\t  Let's trim all the whitespace  \n \t  \n  "
let trimmedString = myString.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet()
)
// Returns "Let's trim all the whitespace"

(Example tested with Swift 3+.)

let myString = "  \t\t  Let's trim all the whitespace  \n \t  \n  "
let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines)
// Returns "Let's trim all the whitespace"

How to use String object in the String format class method

String(format:) is bridged to the -[NSString initWithFormat] method and accepts
the same format specifiers, such as %@ for objects. String is bridged to
NSString automatically, therefore you can use %@ for Swift strings as well. Also note that the Swift Int type corresponds to long in C:

var foo = 0
var str = "str"
let result = String(format: "%ld (%@)", foo, str)

Remove Special Characters in NSString

NSString *unfilteredString = @"!@#$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
NSLog (@"Result: %@", resultString);

TRY THIS IT MAY HELPS YOU

How do I chop/slice/trim off last character in string using Javascript?

You can use the substring function:

let str = "12345.00";str = str.substring(0, str.length - 1);console.log(str);


Related Topics



Leave a reply



Submit