NSString from C to Swift - swift

I code only been a short time and started with Swift .
Can me somebody convert the String in Swift?
Or can me give Tipps?
The main problem lies the selectedSegmentIndex?
NSString *response = [NSString stringWithFormat:#"P%ld%#", tag , button.selectedSegmentIndex?#"L" : #"H"];
greetings

The above code is not C, but Objective-C. If you are not interested in learning about Objective-C at this time and do not need explanation of the above code, this should work:
var response = String(format: "P%ld%#", tag, button.selectedSegmentIndex == 0 ? "L" : "H")

Related

Cannot encode string to utf8 and utf8 to base64 in swift

I'm looking for a way to encode a string to UTF8 and then to base 64 in Swift 3.x
In swift 2.x I was using this way :
let pass: NSString = "test"
let variable: NSString = (pass.dataUsingEncoding(NSUTF8StringEncoding)?.base64EncodedStringWithOptions([]))!
XCode force me to put : NSUTF8StringEncoding.rawValue and then the result is not correct.
If someone has a solution :)
Thank
In Swift 3, it's neater now:
let pass = "test"
let variable = pass.data(using: .utf8)!.base64EncodedString()
And you might want to use better named variables than variable.
If you need to deal with NSString:
let pass: NSString = "test"
let variable = (pass as String).data(using: .utf8)!.base64EncodedString()

Formatting an String

I have an output string in this format .
I need to format the string such that i can display the URL separately and my Content, the description separately. Is there any functions , so i can format them easily ?
The code :
NSLog(#"Description %#", string);
The OUTPUT String:
2013-07-28 11:13:59.083 RSSreader[4915:c07] Description
http://www.apple.com/pr/library/2013/07/23Apple-Reports-Third-Quarter-Results.html?sr=hotnews.rss
Apple today announced financial results for its fiscal 2013 third quarter ended
June 29, 2013. The Company posted quarterly revenue of $35.3 billion and quarterly
net profit of $6.9 billion, or $7.47 per diluted share.
Apple sold 31.2 million iPhones, which set a June quarter record.
You should extract URL from string, then display it in formatted way.
A simple way to extracting URL is regular expressions (RegEX).
After extracting URL you can replace it with nothing:
str = [str stringByReplacingOccurrencesOfString:extractedURL
withString:#""];
You can use this :
https://stackoverflow.com/a/9587987/305135
If description string separated by line break (\n), you can do this:
NSArray *items = [yourString componentsSeparatedByString:#"\n"];
Regex is a good idea.
But there is a default way of detecting URLs within a String in Objective C, NSDataDetector.
NSDataDetector internally uses Regex.
NSString *aString = #"YOUR STRING WITH URLs GOES HERE"
NSDataDetector *aDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *theMatches = [aDetector matchesInString:aString options:0 range:NSMakeRange(0, [aString length])];
for (int anIndex = 0; anIndex < [theMatches count]; anIndex++) {
// If needed, Save this URL for Future Use.
NSString *anURLString = [[[theMatches objectAtIndex:anIndex] URL] absoluteString];
// Replace the Url with Empty String
aTitle = [aTitle stringByReplacingOccurrencesOfString:anURLString withString:#""];
}

How to replace occurrences of multiple strings with multiple other strings [NSString]

NSString *string = [myString stringByReplacingOccurrencesOfString:#"<wow>" withString:someString];
I have this code. Now suppose my app's user enters two different strings I want to replace with two different other strings, how do I achieve that? I don't care if it uses private APIs, i'm developing for the jailbroken platform. My user is going to either enter or or . I want to replace any occurrences of those strings with their respective to-be-replaced-with strings :)
Thanks in advance :P
Both dasblinkenlight’s and Matthias’s answers will work, but they both result in the creation of a couple of intermediate NSStrings; that’s not really a problem if you’re not doing this operation often, but a better approach would look like this.
NSMutableString *myStringMut = [[myString mutableCopy] autorelease];
[myStringMut replaceOccurrencesOfString:#"a" withString:somethingElse];
[myStringMut replaceOccurrencesOfString:#"b" withString:somethingElseElse];
// etc.
You can then use myStringMut as you would’ve used myString, since NSMutableString is an NSString subclass.
The simplest solution is running stringByReplacingOccurrencesOfString twice:
NSString *string = [[myString
stringByReplacingOccurrencesOfString:#"<wow>" withString:someString1]
stringByReplacingOccurrencesOfString:#"<boo>" withString:someString2];
I would just run the string replacing method again
NSString *string = [myString stringByReplacingOccurrencesOfString:#"foo" withString:#"String 1"];
string = [string stringByReplacingOccurrencesOfString:#"bar" withString:#"String 2"];
This works well for me in Swift 3.1
let str = "hi hello hey"
var replacedStr = (str as NSString).replacingOccurrences(of: "hi", with: "Hi")
replacedStr = (replacedStr as NSString).replacingOccurrences(of: "hello", with: "Hello")
replacedStr = (replacedStr as NSString).replacingOccurrences(of: "hey", with: "Hey")
print(replacedStr) // Hi Hello Hey

Localization with variable and constant definition in header file

How do I use NSLocalizedString in this case when I have a header where I define a few parameters, say:
#define appKey #"appKey1 is: %#"
I think I know that my Localizable.strings should look like that:
"blabla" = "appKey1 is: %#"
but how do I use NSLocalizedString? I read that I need to use stringWithFormat, but not sure how...
thanks!
You would define your constant as:
#define appKey NSLocalizedString(#"appKey1 is: %#", #"appkey constant")
Then it should get picked up by the genstrings tool in the usual way.
In the strings file it would then come out like this:
/* appkey constant */
"appKey1 is: %#" = "appKey1 is: %#";
And you would translate just the right hand side.
String literals are acceptable in NSLocalizedStrings. What you need to do is something like
#define appKey NSLocalizedString(BlahBlah , comments);
"BlahBlah" = "appKey1 is: %#";
(Be sure to end your lines with a semi-colon in Localizable.strings, or it will end up being corrupted).
This is how you would do it normally,
NSString * myString = [NSString stringWithFormat:#"appKey1 is: %#",yourAppKeyString];
Since you have it defined you can use it like so
NSString * myString = [NSString stringWithFormat:appKey,yourAppKeyString];
Either case both would fill your myString like so
yourAppKeyString = #"keyString";
myString = #"appKey1 is: keyString";
NSString * myString = [NSString stringWithFormat: NSLocalizedString(#"appKey", #""),yourAppKeyString];

How to Convert NSInteger or NSString to a binary (string) value

Anybody has some code in objective-c to convert a NSInteger or NSString to binary string?
example:
56 -> 111000
There are some code in stackoverflow that try do this, but it doesn´t work.
Thanks
Not sure which examples on SO didn't work for you, but Adam Rosenfield's answer here seems to work. I've updated it to remove a compiler warning:
// Original author Adam Rosenfield... SO Question 655792
NSInteger theNumber = 56;
NSMutableString *str = [NSMutableString string];
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1)
{
// Prepend "0" or "1", depending on the bit
[str insertString:((numberCopy & 1) ? #"1" : #"0") atIndex:0];
}
NSLog(#"Binary version: %#", str);
Tooting my own horn a bit here...
I've written a math framework called CHMath that deals with arbitrarily large integers. One of the things it does is allows the user to create a CHNumber from a string, and get its binary representation as a string. For example:
CHNumber * t = [CHNumber numberWithString:#"56"];
NSString * binaryT = [t binaryStringValue];
NSLog(#"Binary value of %#: %#", t, binaryT);
Logs:
2009-12-15 10:36:10.595 otest-x86_64[21918:903] Binary value of 56: 0111000
The framework is freely available on its Github repository.