1

I have a Swift app that is scanning a barcode. The barcode sometimes contains a control character at the beginning which is not visible: \u{1D}

I use this method to strip the value from the string but I am looking for something more robust in case some other control characters come up or are inside the string and not at the beginning.

if(articleFilter.hasPrefix("\u{1D}")){
    let stringSize = articleFilter.count - 6
    finalArticleCode = String(articleFilter.suffix(stringSize))
}
Max B
  • 193
  • 1
  • 15

5 Answers5

2

You can use extension to filter other characters except for the numeric.

extension String {

  func filterNonNumeric() -> String {
    return self.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
  }
}

var str = "\u{1D}01000000000010"
self.sampleLabel.text = str.filterNonNumeric()

The result will be:

Nirbhay Singh
  • 1,204
  • 1
  • 12
  • 16
Aira Samson
  • 226
  • 2
  • 10
2

Removing characters from the start and end is called trimming. And the control characters are:

https://developer.apple.com/documentation/foundation/nscharacterset/1416371-controlcharacters

So, like this:

let articleFilterNew = articleFilter.trimmingCharacters(in: .controlCharacters)
matt
  • 515,959
  • 87
  • 875
  • 1,141
1

Maybe You can use Replacing String protocol

articleFilter = articleFilter.replacingOccurrences(of: "\u{1D}", with: "")

I think it will solve your problem.

pkamb
  • 33,281
  • 23
  • 160
  • 191
KpStar
  • 122
  • 7
  • Is there also a way to use replacingoccurenzces() with .controlCharacters? When I try finalArticleCode = articleFilter.replacingOccurrences(of: .controlCharacters, with: "") I get "Type of expression is ambiguous without more context" as error – Max B Dec 11 '19 at 01:20
0

It is very simple by using trimming Characters

var str =  "\u{1D}01000000000010"

let filteredOne = str.trimmingCharacters(in: .controlCharacters)
Sandu
  • 436
  • 4
  • 8
0

For Objective C, I have used the following code and it works

-(NSString *)normalizeText:(NSString *)text {
    NSString *normalizedText = [[text componentsSeparatedByCharactersInSet:NSCharacterSet.controlCharacterSet] componentsJoinedByString:@""];
    NSLog (@"Result: %@", normalizedText);
    
    return normalizedText;
}

For Swift, it is similarly something like

func normalizeText(text: String) -> String {
return text.components(separatedBy: .controlCharacters).joined()
}
xuanloctn
  • 81
  • 1
  • 1
  • 8