The array value should be sort like (alphabetic, numbers and special characters)
let words = ["23412334","&234@fwv","Kofi", "Abena", "Peter", "Kweku", "Akosua"]
func sortedNumbersLast(words: [String]) -> [String] {
var startsWithDigit = [String]()
var startsWithCharacter = [String]()
var startsWithSymbol = [String]()
for word in words {
if let first = word.characters.first {
if first >= "0" && first <= "9" {
startsWithDigit.append(word)
}
else {
if(!(first >= "a" && first <= "z") && !(first >= "A" && first <= "Z") ){
startsWithSymbol.append(word)
}else{
startsWithCharacter.append(word)
}
}
}
}
return startsWithCharacter.sorted(by: <) + startsWithDigit.sorted(by: <) + startsWithSymbol.sorted()
}
print(sortedNumbersLast(words: words))
["Abena", "Akosua", "Kofi", "Kweku", "Peter", "23412334", "&234@fwv"]
Modified Answer
In javascript sorting strings with numbers and special characters
If you like to sort by groups, like letters and/or digits, you could take sorting with options of String#localeCompare
.
var array = ["AB_UI08","AB_UI03","AB_UI07","AB_UI04","AB_UI05","AB_UI014","AB_UI01","AB_UI09","AB_UI010","AB_UI011","AB_UI012","AB_UI013","AB_UI06","AB_UI016","AB_UI07","AB_UI018","AB_UI019","AB_UI015","AB_UI020","AB_UI02"];
console.log(array.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })));
.as-console-wrapper { max-height: 100% !important; top: 0; }
C array sorting ignoring special characters
You can pre-process the string and use strcmp
to compare the processed string:
// Inside the two-layer for loop
char newb[size], newz[size];
int ib, iz, tb = 0, tz = 0;
for (ib = 0; processNames[b][ib] != '\0'; ib++){
if (isalpha(processNames[b][ib])) {
newb[tb++] = processNames[b][ib];
}
}
newb[tb] = 0;
for (iz = 0; processNames[z][iz] != '\0'; iz++){
if (isalpha(processNames[z][iz])) {
newz[tz++] = processNames[z][iz];
}
}
newz[tz] = 0;
if (strcmp(newb, newz)) {
// swap the ORIGINAL string here
}
The above code is what I came up with at first. It is very inefficient and is not recommended. Alternatively, you can write your own mystrcmp()
implementation:
int mystrcmp(const char* a, const char *b){
while (*a && *b) {
while (*a && !isalpha(*a)) a++;
while (*b && !isalpha(*b)) b++;
if (*a - *b) return *a - *b;
a++, b++;
}
return *a - *b;
}
how to Json Dictionary Array value sorting like (A-z, 0-9 and special char) in Swift
Here you go
func isDigit(c: UnicodeScalar) -> Bool {
let digits = CharacterSet.decimalDigits
return digits.contains(c)
}
func isAlphabet(c : UnicodeScalar) -> Bool {
let letters = CharacterSet.letters
return letters.contains(c)
}
func getSpecialSorted ( arrayOfStudents : [[String : String]]) -> [[String : String]] {
var arrayStartingWithAlphabets = [[String : String]]()
var arrayStartingWithDigits = [[String : String]]()
var arrayStartingWithAlphanumeric = [[String : String]]()
for student in arrayOfStudents {
if isDigit(c: (student["fullName"]?.unicodeScalars.first!)!) {
arrayStartingWithDigits.append(student)
} else if isAlphabet(c:(student["fullName"]?.unicodeScalars.first!)!) {
arrayStartingWithAlphabets.append(student)
} else {
arrayStartingWithAlphanumeric.append(student)
}
}
arrayStartingWithAlphabets = getNormalSorted(array : arrayStartingWithAlphabets)
arrayStartingWithDigits = getNormalSorted(array: arrayStartingWithDigits)
arrayStartingWithAlphanumeric = getNormalSorted(array: arrayStartingWithAlphanumeric)
return arrayStartingWithAlphabets + arrayStartingWithDigits + arrayStartingWithAlphanumeric
}
func getNormalSorted(array : [[String : String]]) -> [[String: String]]{
let sortedArray = array.sorted { (firstStudent, secondStudent) -> Bool in
if let firstName = firstStudent["fullName"] , let
secondName = secondStudent["fullName"] {
return firstName.compare(secondName) == ComparisonResult.orderedAscending
}
return false
}
return sortedArray
}
Also you need to change your declaration like
let students = [["fullName": "23412334", "number": "39485793"],["fullName": "&234@fwv", "number": "395793"],["fullName": "Abena", "number": "3572343"],["fullName": "Peter", "number": "394568993"],["fullName": "Kweku", "number": "309693"]]
let sortedResults = getSpecialSorted(arrayOfStudents: students)
print(sortedResults)
In Swift, how do I sort an array of strings and have strings of numbers, symbols, etc. always come after alphabetic strings?
The key is to write your "is ordered before" function to do whatever you want. For example, if by digits, you mean "0"..."9", then something like this is probably what you want:
func isDigit(c: Character) -> Bool {
return "0" <= c && c <= "9"
}
func sortedLettersFirst(lhs: String, rhs: String) -> Bool {
for (lc, rc) in zip(lhs.characters, rhs.characters) {
if lc == rc { continue }
if isDigit(lc) && !isDigit(rc) {
return false
}
if !isDigit(lc) && isDigit(rc) {
return true
}
return lc < rc
}
return lhs.characters.count < rhs.characters.count
}
words.sort(sortedLettersFirst)
Of course, if by "digit" you mean "unicode digits", then see What is the replacement for isDigit() for characters in Swift? for a different approach to isDigit
. But ultimately, the point is to make whatever rule you want in your isOrderedBefore
function, and pass that to sort()
.
Related Topics
Avcapturevideopreviewlayer Add Overlays and Capture Photo in iOS
Swift - Update/Refresh Label That Displays Time
iOS Sound Not Playing in Swift
Nsurlsession/Nsurlconnection Http Load Failed (Kcfstreamerrordomainssl, -9802) on a Subdomain
Problems with Cropping a Uiimage in Swift
Wkwebview Decidepolicyfornavigationaction Being Call After the Long Press Recogniser Ended
Swiftui Animation and Subsequent Reverse Animation to Original State
Xcode 11 Archive Gives Phasescriptexecution Failed
Game Exits from Pause State After Resuming It from Background in Swift
Records, Zone Doesn't Displayed in Dashboard and Delete Zone Issue Cloudkit
Swiftui - Scrollviewreader's Scrollto Does Not Scroll
iOS Swift Flood Fill Algorithm
Navigationlink Inside Lazyvgrid Cycles All Entries on Back, Swiftui
Can't Dismiss Navigation Controller in Swift
Cannot Invoke 'Decode' with an Argument List of Type '(T, From: Data)'