NSString+PJR.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. //
  2. // NSString+PJR.m
  3. // Lib
  4. //
  5. // Created by Paritosh on 15/05/14.
  6. //
  7. // * All rights reserved.
  8. /*
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions are met:
  11. * * Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. * * Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. * * Neither the name of the <organization> nor the
  17. * names of its contributors may be used to endorse or promote products
  18. * derived from this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  21. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  22. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  23. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  24. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  25. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  26. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  27. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  29. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. *
  31. */
  32. #import "NSString+PJR.h"
  33. #import <CommonCrypto/CommonDigest.h>
  34. @implementation NSString (PJR)
  35. // Checking if String is Empty
  36. -(BOOL)isBlank
  37. {
  38. if ([[self removeWhiteSpacesFromString] isEqualToString:@""]) {
  39. return NO;
  40. }
  41. if (self.length<6) {
  42. return NO;
  43. }
  44. if (self.length>16) {
  45. return NO;
  46. }
  47. return YES;
  48. //return ([[self removeWhiteSpacesFromString] isEqualToString:@""]) || self.length<6 ? YES : NO;
  49. }
  50. //Checking if String is empty or nil
  51. -(BOOL)isValid
  52. {
  53. return ([[self removeWhiteSpacesFromString] isEqualToString:@""] || self == nil || [self isEqualToString:@"(null)"]) ? NO :YES;
  54. }
  55. // remove white spaces from String
  56. - (NSString *)removeWhiteSpacesFromString
  57. {
  58. NSString *trimmedString = [self stringByTrimmingCharactersInSet:
  59. [NSCharacterSet whitespaceAndNewlineCharacterSet]];
  60. return trimmedString;
  61. }
  62. // Counts number of Words in String
  63. - (NSUInteger)countNumberOfWords
  64. {
  65. NSScanner *scanner = [NSScanner scannerWithString:self];
  66. NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
  67. NSUInteger count = 0;
  68. while ([scanner scanUpToCharactersFromSet: whiteSpace intoString: nil]) {
  69. count++;
  70. }
  71. return count;
  72. }
  73. // If string contains substring
  74. - (BOOL)containsString:(NSString *)subString
  75. {
  76. return ([self rangeOfString:subString].location == NSNotFound) ? NO : YES;
  77. }
  78. // If my string starts with given string
  79. - (BOOL)isBeginsWith:(NSString *)string
  80. {
  81. return ([self hasPrefix:string]) ? YES : NO;
  82. }
  83. // If my string ends with given string
  84. - (BOOL)isEndssWith:(NSString *)string
  85. {
  86. return ([self hasSuffix:string]) ? YES : NO;
  87. }
  88. // Replace particular characters in my string with new character
  89. - (NSString *)replaceCharcter:(NSString *)olderChar withCharcter:(NSString *)newerChar
  90. {
  91. return [self stringByReplacingOccurrencesOfString:olderChar withString:newerChar];
  92. }
  93. // Get Substring from particular location to given lenght
  94. - (NSString*)getSubstringFrom:(NSInteger)begin to:(NSInteger)end
  95. {
  96. NSRange r;
  97. r.location = begin;
  98. r.length = end - begin;
  99. return [self substringWithRange:r];
  100. }
  101. // Add substring to main String
  102. - (NSString *)addString:(NSString *)string
  103. {
  104. if(!string || string.length == 0)
  105. return self;
  106. return [self stringByAppendingString:string];
  107. }
  108. // Remove particular sub string from main string
  109. -(NSString *)removeSubString:(NSString *)subString
  110. {
  111. if ([self containsString:subString])
  112. {
  113. NSRange range = [self rangeOfString:subString];
  114. return [self stringByReplacingCharactersInRange:range withString:@""];
  115. }
  116. return self;
  117. }
  118. // If my string contains ony letters
  119. - (BOOL)containsOnlyLetters
  120. {
  121. NSCharacterSet *letterCharacterset = [[NSCharacterSet letterCharacterSet] invertedSet];
  122. return ([self rangeOfCharacterFromSet:letterCharacterset].location == NSNotFound);
  123. }
  124. // If my string contains only numbers
  125. - (BOOL)containsOnlyNumbers
  126. {
  127. NSCharacterSet *numbersCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
  128. return ([self rangeOfCharacterFromSet:numbersCharacterSet].location == NSNotFound);
  129. }
  130. // If my string contains letters and numbers
  131. - (BOOL)containsOnlyNumbersAndLetters
  132. {
  133. NSCharacterSet *numAndLetterCharSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
  134. return ([self rangeOfCharacterFromSet:numAndLetterCharSet].location == NSNotFound);
  135. }
  136. // If my string is available in particular array
  137. - (BOOL)isInThisarray:(NSArray*)array
  138. {
  139. for(NSString *string in array) {
  140. if([self isEqualToString:string]) {
  141. return YES;
  142. }
  143. }
  144. return NO;
  145. }
  146. // Get String from array
  147. + (NSString *)getStringFromArray:(NSArray *)array
  148. {
  149. return [array componentsJoinedByString:@" "];
  150. }
  151. // Convert Array from my String
  152. - (NSArray *)getArray
  153. {
  154. return [self componentsSeparatedByString:@" "];
  155. }
  156. // Get My Application Version number
  157. + (NSString *)getMyApplicationVersion
  158. {
  159. NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
  160. NSString *version = [info objectForKey:@"CFBundleShortVersionString"];
  161. return version;
  162. }
  163. // Get My Application name
  164. + (NSString *)getMyApplicationName
  165. {
  166. NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
  167. NSString *name = [info objectForKey:@"CFBundleDisplayName"];
  168. return name;
  169. }
  170. // Convert string to NSData
  171. - (NSData *)convertToData
  172. {
  173. return [self dataUsingEncoding:NSUTF8StringEncoding];
  174. }
  175. // Get String from NSData
  176. + (NSString *)getStringFromData:(NSData *)data
  177. {
  178. return [[NSString alloc] initWithData:data
  179. encoding:NSUTF8StringEncoding];
  180. }
  181. // Is Valid Email
  182. - (BOOL)isValidEmail
  183. {
  184. NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
  185. NSPredicate *emailTestPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
  186. return [emailTestPredicate evaluateWithObject:self];
  187. }
  188. // Is Valid Phone
  189. - (BOOL)isVAlidPhoneNumber
  190. {
  191. NSString *regex = @"^((13[0-9])|(17[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
  192. NSPredicate *telNumPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
  193. return [telNumPre evaluateWithObject:self];
  194. }
  195. // Is Valid URL
  196. - (BOOL)isValidUrl
  197. {
  198. NSString *regex =@"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
  199. NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
  200. return [urlTest evaluateWithObject:self];
  201. }
  202. - (BOOL)isPassword{
  203. NSString * regex = @"^[A-Za-z0-9]{6,12}$";
  204. NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
  205. return [pred evaluateWithObject:self];
  206. }
  207. - (NSString*) urlEncodedString {
  208. CFStringRef encodedCFString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
  209. (__bridge CFStringRef) self,
  210. nil,
  211. CFSTR("?!@#$^&%*+,:;='\"`<>()[]{}/\\| "),
  212. kCFStringEncodingUTF8);
  213. NSString *encodedString = [[NSString alloc] initWithString:(__bridge_transfer NSString*) encodedCFString];
  214. if(!encodedString)
  215. encodedString = @"";
  216. return encodedString;
  217. }
  218. - (NSString*) urlDecodedString {
  219. CFStringRef decodedCFString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
  220. (__bridge CFStringRef) self,
  221. CFSTR(""),
  222. kCFStringEncodingUTF8);
  223. // We need to replace "+" with " " because the CF method above doesn't do it
  224. NSString *decodedString = [[NSString alloc] initWithString:(__bridge_transfer NSString*) decodedCFString];
  225. return (!decodedString) ? @"" : [decodedString stringByReplacingOccurrencesOfString:@"+" withString:@" "];
  226. }
  227. -(NSString *)md5
  228. {
  229. const char *cStr = [self UTF8String];
  230. unsigned char result[CC_MD5_DIGEST_LENGTH];
  231. CC_MD5(cStr, (int)strlen(cStr), result); // This is the md5 call
  232. return [NSString stringWithFormat:
  233. @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
  234. result[0], result[1], result[2], result[3],
  235. result[4], result[5], result[6], result[7],
  236. result[8], result[9], result[10], result[11],
  237. result[12], result[13], result[14], result[15]
  238. ];
  239. }
  240. -(NSString *)sha1
  241. {
  242. const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
  243. NSData *data = [NSData dataWithBytes:cstr length:self.length];
  244. uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  245. CC_SHA1(data.bytes, (int)data.length, digest);
  246. NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  247. for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
  248. [output appendFormat:@"%02x", digest[i]];
  249. }
  250. return output;
  251. }
  252. - (NSString*)base64Encode
  253. {
  254. //1.将需要加密的数据转成二进制,因为Base64的编码和解码都是针对二进制的
  255. NSData*data = [self dataUsingEncoding:NSUTF8StringEncoding];
  256. //2.把二进制数据编码之后,直接转成字符串
  257. NSString*encodeString = [data base64EncodedStringWithOptions:0];
  258. //3.返回结果returnencodeStr;
  259. return encodeString;
  260. }
  261. - (NSString*)base64Decode
  262. {
  263. if(self.length==0){
  264. return nil;
  265. }
  266. //1.把编码之后的字符串解码成二进制
  267. NSData*data = [[NSData alloc]initWithBase64EncodedString:self options:0];
  268. //2.把解码之后的二进制转换成字符串
  269. NSString*encodeString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  270. //3. 返回结果returndecodeStr;
  271. return encodeString;
  272. }
  273. - (NSString *)returnCompleteString
  274. {
  275. return ([self isKindOfClass:[NSNull class]] || [self isEqualToString:@"(null)"]) ? @"" : self;
  276. }
  277. @end