is there a method to verify if a NSString haven't characters?
example of string without characters can be:
#"" or #" " or #"\n " or #"\n\n ", I want cosider these strings as empty strings and print a nslog that say me that these are emty, what kind of control I should use?
You can use this test:
if ([[myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
// The string is empty
}
You can iterate through every character in the string and check if it is the space (" ") or newline ("\n") character. If not, return false. Else if you search through the whole string and didn't return false, it is "empty".
Something like this:
NSString* myStr = #"A STRING";
for(int i = 0; i < [myStr length]; i++)
{
if(!(([myStr characterAtIndex:i] == #' ') || ([myStr characterAtIndex:i] == #'\n')))
{
return false;
}
}
Related
How to check if a string contain a letter 'b' after letter 'a'?
For example :
if the string is 'abcd' then it's return 'true'
if the string is 'acbd' then it's return 'true'
if the string is 'bacb' then it's return 'true'
if the string is 'bcda' then it's return 'false'
NSString *str = #"123abcd";
NSRange ra = [str rangeOfString:#"a"];
NSRange rb = [str rangeOfString:#"b"];
if ((ra.location == NSNotFound) || (ra.location == NSNotFound)) {
NSLog(#"string is missing one or both specified characters");
} else if (ra.location < rb.location) {
NSLog(#"a comes before b");
} else {
NSLog(#"a comes after b");
}
Be careful, if "a" or "b" occurs more than once this might not work properly.
You can use if ([string containsString:#"ab"])
I am implementing csv splitting in my project . can I know how to implement CSV splitting in ios. say for example i have a string #"one,\"two,three\",four" . I need output as below in an array format which containts 3 element
one
two,three
four
You can use this code but, it is not proper way:
NSString *StrDataOfCSV=#"one,\"two,three\",four";
NSMutableArray * csvArray= [[NSMutableArray alloc]init];
NSArray * firstSeparated=[StrDataOfCSV componentsSeparatedByString: #"\","];
for (NSString * strCom in firstSeparated) {
NSArray * arrCom=[strCom componentsSeparatedByString:#",\""];
[csvArray addObjectsFromArray:arrCom];
}
Something like this to "normalize" your input string, replacing the commas with a new separator character, one that you can guarantee won't appear in your input (e.g. a |), and removing the quotes from the quoted fields:
char *cbCSVRecord = "one,\"two,three\",four";
bool bQuotedField = false;
// normalize
for (int i = 0,j = 0;i < (int)strlen(cbCSVRecord);i++)
{
if ((cbCSVRecord[i] == '\n') || (cbCSVRecord[i] == '\r'))
cbCSVRecord[i] = '\0';
// Not a double quote?
if (cbCSVRecord[i] != '"')
{
// if a comma NOT within a quoted field, replace with a new separator
if ((cbCSVRecord[i] == ',') && (!bQuotedField))
cbCSVRecord[i] = '|';
// new output
cbCSVRecord[j] = cbCSVRecord[i];
j++;
}
// Is a double quote, toggle bQuotedField
else
{
if (!bQuotedField)
bQuotedField = true;
else
bQuotedField = false;
}
}
cbCSVRecord[j] = '\0';
please note that I roughed out this code, and it is plain C code. It should either work or have you pretty close.
An input of #"one,\"two,three\",four" should become #"one|two,three|four", and you can then use:
NSArray *listItems = [list componentsSeparatedByString:#"|"];
Use NSString's componentsSeparatedByString:
NSString *list = #"Karin, Carrie, David";
NSArray *listItems = [list componentsSeparatedByString:#", "];
I need to count characters in string before some string and after some string. For example, I have string "This is example string" and I need to know howmany characters are before word "example" (it is 8 chars in this case) and how many characters are after word "example" (7 in that case...). My idea was to loop that string and count every character, but how to stop it before that requied word? Thanks for every idea!
check this out
NSString *sample = #"This is example string";
NSRange b = [sample rangeOfString:#"example"];
if (b.location != NSNotFound) {
NSLog(#"%d characters before", b.location);
NSLog(#"%d characters after", [sample length] - b.location - b.length);
}
I'm developing an iPhone app. In a label, I want to show an user's first letter of the name uppercase. How do I do that?
If there is only one word String, then use the method
-capitalized
let capitalizedString = myStr.capitalized // capitalizes every word
Otherwise, for multi word strings, you have to extract first character and make only that character upper case.
(2014-07-24: Currently accepted answer is not correct) The question is very specific: Make the first letter uppercase, leave the rest lowercase. Using capitalizedString produces a different result: “Capitalized String” instead of “Capitalized string”. There is another variant depending on the locale, which is capitalizedStringWithLocale, but it's not correct for spanish, right now it's using the same rules as in english, so this is how I'm doing it for spanish:
NSString *abc = #"this is test";
abc = [NSString stringWithFormat:#"%#%#",[[abc substringToIndex:1] uppercaseString],[abc substringFromIndex:1] ];
NSLog(#"abc = %#",abc);
In case someone is still interested in 2016, here is a Swift 3 extension:
extension String {
func capitalizedFirst() -> String {
let first = self[self.startIndex ..< self.index(startIndex, offsetBy: 1)]
let rest = self[self.index(startIndex, offsetBy: 1) ..< self.endIndex]
return first.uppercased() + rest.lowercased()
}
func capitalizedFirst(with: Locale?) -> String {
let first = self[self.startIndex ..< self.index(startIndex, offsetBy: 1)]
let rest = self[self.index(startIndex, offsetBy: 1) ..< self.endIndex]
return first.uppercased(with: with) + rest.lowercased(with: with)
}
}
Then you use it exactly as you would for the usual uppercased() or capitalized():
myString.capitalizedFirst() or myString.capitalizedFirst(with: Locale.current)
Simply
- (NSString *)capitalizeFirstLetterOnlyOfString:(NSString *)string{
NSMutableString *result = [string lowercaseString].mutableCopy;
[result replaceCharactersInRange:NSMakeRange(0, 1) withString:[[result substringToIndex:1] capitalizedString]];
return result;
}
This is for your NSString+Util category...
- (NSString *) capitalizedFirstLetter {
NSString *retVal;
if (self.length < 2) {
retVal = self.capitalizedString;
} else {
retVal = string(#"%#%#",[[self substringToIndex:1] uppercaseString],[self substringFromIndex:1]);
}
return retVal;
}
You can do that with NSString stringWithFormat, of course. I use this weirdness:
#define string(...) \
[NSString stringWithFormat:__VA_ARGS__]
As an extension to the accepted answer
capitalizedString is used for making uppercase letters .
NSString *capitalizedString = [myStr capitalizedString]; // capitalizes every word
But if you have many words in a string and wants to get only first character as upper case use the below solution
NSString *firstCapitalChar = [[string substringToIndex:1] capitalizedString];
NSString *capString = [string stringByReplacingCharactersInRange:NSMakeRange(0,1) withString: capString];
// extract first character and make only that character upper case.
here's a swift extension for it
extension NSString {
func capitalizeFirstLetter() -> NSString {
return self.length > 1 ?
self.substringToIndex(1).capitalizedString + self.substringFromIndex(1) :
self.capitalizedString
}
}
This is how it worked for me:
NSString *serverString = jsonObject[#"info"];
NSMutableString *textToDisplay = [NSMutableString stringWithFormat:#"%#", serverString];
[textToDisplay replaceCharactersInRange:NSMakeRange(0, 1) withString:[textToDisplay substringToIndex:1].capitalizedString];
cell.infoLabel.text = textToDisplay;
Hope it helps.
Swift:
let userName = "hard CODE"
yourLabel.text = userName.localizedUppercaseString
I recommend using this localised version of uppercase, since names are locale sensitive.
I have a NSString like this:
http://www.
but I want to transform it to:
http%3A%2F%2Fwww.
How can I do this?
To escape the characters you want is a little more work.
Example code
iOS7 and above:
NSString *unescaped = #"http://www";
NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSLog(#"escapedString: %#", escapedString);
NSLog output:
escapedString: http%3A%2F%2Fwww
The following are useful URL encoding character sets:
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?#\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?#[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?#[\]^`
Creating a characterset combining all of the above:
NSCharacterSet *URLCombinedCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:#" \"#%/:<>?#[\\]^`{|}"] invertedSet];
Creating a Base64
In the case of Base64 characterset:
NSCharacterSet *URLBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:#"/+=\n"] invertedSet];
For Swift 3.0:
var escapedString = originalString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)
For Swift 2.x:
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
Note: stringByAddingPercentEncodingWithAllowedCharacters will also encode UTF-8 characters needing encoding.
Pre iOS7 use Core Foundation
Using Core Foundation With ARC:
NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef) unescaped,
NULL,
CFSTR("!*'();:#&=+$,/?%#[]\" "),
kCFStringEncodingUTF8));
Using Core Foundation Without ARC:
NSString *escapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unescaped,
NULL,
CFSTR("!*'();:#&=+$,/?%#[]\" "),
kCFStringEncodingUTF8);
Note: -stringByAddingPercentEscapesUsingEncoding will not produce the correct encoding, in this case it will not encode anything returning the same string.
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding encodes 14 characrters:
`#%^{}[]|\"<> plus the space character as percent escaped.
testString:
" `~!##$%^&*()_+-={}[]|\\:;\"'<,>.?/AZaz"
encodedString:
"%20%60~!#%23$%25%5E&*()_+-=%7B%7D%5B%5D%7C%5C:;%22'%3C,%3E.?/AZaz"
Note: consider if this set of characters meet your needs, if not change them as needed.
RFC 3986 characters requiring encoding (% added since it is the encoding prefix character):
"!#$&'()*+,/:;=?#[]%"
Some "unreserved characters" are additionally encoded:
"\n\r \"%-.<>\^_`{|}~"
It's called URL encoding. More here.
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding));
}
This is not my solution. Someone else wrote in stackoverflow but I have forgotten how.
Somehow this solution works "well". It handles diacritic, chinese characters, and pretty much anything else.
- (NSString *) URLEncodedString {
NSMutableString * output = [NSMutableString string];
const char * source = [self UTF8String];
int sourceLen = strlen(source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = (const unsigned char)source[i];
if (false && thisChar == ' '){
[output appendString:#"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:#"%c", thisChar];
} else {
[output appendFormat:#"%%%02X", thisChar];
}
}
return output;
}
If someone would tell me who wrote this code, I'll really appreciate it. Basically he has some explanation why this encoded string will decode exactly as it wish.
I modified his solution a little. I like space to be represented with %20 rather than +. That's all.
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NUL,(CFStringRef)#"parameter",NULL,(CFStringRef)#"!*'();#&+$,/?%#[]~=_-.:",kCFStringEncodingUTF8 );
NSURL * url = [[NSURL alloc] initWithString:[#"address here" stringByAppendingFormat:#"?cid=%#",encodedString, nil]];
This can work in Objective C ARC.Use CFBridgingRelease to cast a Core Foundation-style object as an Objective-C object and transfer ownership of the object to ARC .See Function CFBridgingRelease here.
+ (NSString *)encodeUrlString:(NSString *)string {
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes
(kCFAllocatorDefault,
(__bridge CFStringRef)string,
NULL,
CFSTR("!*'();:#&=+$,/?%#[]"),
kCFStringEncodingUTF8)
);}
Swift iOS:
Just For Information : I have used this:
extension String {
func urlEncode() -> CFString {
return CFURLCreateStringByAddingPercentEscapes(
nil,
self,
nil,
"!*'();:#&=+$,/?%#[]",
CFStringBuiltInEncodings.UTF8.rawValue
)
}
}// end extension String
Here's what I use. Note you have to use the #autoreleasepool feature or the program might crash or lockup the IDE. I had to restart my IDE three times until I realized the fix. It appears that this code is ARC compliant.
This question has been asked many times, and many answers given, but sadly all of the ones selected (and a few others suggested) are wrong.
Here's the test string that I used: This is my 123+ test & test2. Got it?!
These are my Objective C++ class methods:
static NSString * urlDecode(NSString *stringToDecode) {
NSString *result = [stringToDecode stringByReplacingOccurrencesOfString:#"+" withString:#" "];
result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return result;
}
static NSString * urlEncode(NSString *stringToEncode) {
#autoreleasepool {
NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)stringToEncode,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
kCFStringEncodingUTF8
));
result = [result stringByReplacingOccurrencesOfString:#"%20" withString:#"+"];
return result;
}
}
NSString *str = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)yourString,
NULL,
CFSTR("/:"),
kCFStringEncodingUTF8);
You will need to release or autorelease str yourself.
Google implements this in their Google Toolbox for Mac. So that's a good place to peak how they're doing it. Another option is to include the Toolbox and use their implementation.
Checkout the implementation here. (Which comes down to exactly what people have been posting here).
This is how I am doing this in swift.
extension String {
func encodeURIComponent() -> String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
}
func decodeURIComponent() -> String {
return self.componentsSeparatedByString("+").joinWithSeparator(" ").stringByRemovingPercentEncoding!
}
}
This is what I did on Swift 5:
func formatPassword() -> String {
var output = "";
for ch in self {
let char = String(ch)
switch ch {
case " ":
output.append("+")
break
case ".", "-", "_", "~", "a"..."z", "A"..."Z", "0"..."9":
output.append(char)
break
default:
print(ch)
let unicode = char.unicodeScalars.first?.value ?? 0
let unicodeValue = NSNumber(value: unicode).intValue
let hexValue = String(format: "%02X", arguments: [unicodeValue])
output = output.appendingFormat("%%%#", hexValue)
}
}
return output as String
}
Then I called this function where I defined my password.
//use NSString instance method like this:
+ (NSString *)encodeURIComponent:(NSString *)string
{
NSString *s = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return s;
}
+ (NSString *)decodeURIComponent:(NSString *)string
{
NSString *s = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return s;
}
remember,you should only do encode or decode for your parameter value, not all the url you request.
int strLength = 0;
NSString *urlStr = #"http://www";
NSLog(#" urlStr : %#", urlStr );
NSMutableString *mutableUrlStr = [urlStr mutableCopy];
NSLog(#" mutableUrlStr : %#", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:#":" withString:#"%3A" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(#" mutableUrlStr : %#", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:#"/" withString:#"%2F" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(#" mutableUrlStr : %#", mutableUrlStr );