NSString using
NSString is immutable, which doesn't mean that it can't be manipulated. Immutable means that once NSString is created, it can't be changed. You can perform various operations on it, such as generating new strings, finding characters or comparing it with other strings, but you can't change it by deleting or adding characters
Creation of NSString
//Create using literal form
NSString *str1 = @"str";
//Create an empty string and assign a value
NSString *str2 = [[NSString alloc] init];
str2 = @"str";
//Usage: - (instancetype)initWithString:(NSString *)representation;
//Note: if the method becomes [[NSString alloc] initWithString:@"str"]; form, the system will prompt to create the string in literal form
NSString *str3 = [[NSString alloc] initWithString:str1];
//Creating strings with standard c: initWithCString method
char *CString = "C-String!";
NSString *str4 = [NSString stringWithCString:CString encoding:NSUTF8StringEncoding];
//Create format string
NSInteger num1 = 5;
CGFloat num2 = 5.5;
NSString *strTemp = @"temp";
double num3 = 6.0;
long num4 = 7.0;
int num5 = 8;
float num6 = 8.5;
NSNumber *num7 = [NSNumber numberWithInteger:num1];
NSString *str5 = [NSString stringWithFormat:@"NSInteger:%ld,CGFloat:%f,NSString:%@,double:%f,long:%lu,int:%d,float:%f,NSNumber:%@",num1,num2,strTemp,num3,num4,num5,num6,num7];
//Output results: NSInteger:5,CGFloat:5.500000,NSString:temp,double:6.000000,long:7,int:8,float:8.500000,NSNumber:5
CGFloat pi = 3.1415926535898;
NSString *str6 = [NSString stringWithFormat:@".2f:%.2f ; .3f:%.3f",pi,pi];
//The output results were:.2f:3.14;.3f:3.142
Get string length
//Use length Get string length,Whether it's letters,number,Chinese characters,Symbol,Unicode Length is1,emoji The length of is2
NSString *strChar = @"Chinese";
NSString *strNumber = @"1";
NSString *strLetter = @"a";
NSString *strEmoji = @"��"; //Clover emoji
NSString *strUnicode = @"\u2107";//ℇ
NSLog(@"strChar:%ld,strNumber:%ld,strLetter:%ld,strEmoji:%ld,strUnicode:%ld",strChar.length,strNumber.length,strLetter.length,strEmoji.length,strUnicode.length);
/*
//Output results
//strChar:1,strNumber:1,strLetter:1,strEmoji:2,strUnicode:1
*/
String comparison using isEqualToString: method
NSString *str1 = [NSString stringWithFormat:@"1"];
//0xa000000000000311
NSString *str2 = @"1";
//0x000000010bc61068
if ([str1 isEqualToString:str2])
{
NSLog(@"str1 is equal to string str2");
}else
{
NSLog(@"str1 is not equal to string str2");
}
//Output result: str1 is equal to string str2
if (str1 == str2)
{
NSLog(@"str1 = str2");
}else
{
NSLog(@"str ≠ str2");
}
//Output result: str ≠ str2
//***Attention***
//isEqualToString: should be used when comparing whether two strings are equal, not just the pointer value of the string
//This is because the "= =" operator only judges the pointer value of str1 and str2 strings, not the object they refer to. Because str1 and str2 are different strings, the "= =" operator will think that they are different in this way of comparison
//Therefore, if you want to check whether two objects (str1 and str2) are the same thing, you should use the operator "=". If you just want to check whether the two strings are equal (that is, whether the contents of the two strings are the same), use the isEqualToString: method
Use of compare
NSString *str1 = @"a";
NSString *str2 = @"b";
NSString *str3 = @"A";
//- (NSComparisonResult)compare:(NSString *)string;
/*
NSOrderedAscending = -1L, s1 < s2
NSOrderedSame, s1 = s2
NSOrderedDescending s1 > s2
*/
NSComparisonResult result = [str1 compare:str2];
if (result == -1)
{
NSLog(@"result:%ld,%@ < %@",result,str1,str2);
}else if (result == 0)
{
NSLog(@"result:%ld,%@ = %@",result,str1,str2);
}else
{
NSLog(@"result:%ld,%@ > %@",result,str1,str2);
}
//result:-1,a < b
/*************************************************/
//- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
//The options parameter is a mask. You can use the bit or bitwise-OR operator (|) to add option markers
/*
options parameter
typedef NS_OPTIONS(NSUInteger, NSStringCompareOptions) {
//Case insensitive comparison
NSCaseInsensitiveSearch = 1,
//Byte by byte comparison case sensitive
NSLiteralSearch = 2,
//Search from end of string
NSBackwardsSearch = 4,
//Search restricted string
NSAnchoredSearch = 8,
//Work out the order based on the numbers in the string.
NSNumericSearch = 64,
//Ignore comparison of "-" symbols
NSDiacriticInsensitiveSearch NS_ENUM_AVAILABLE(10_5, 2_0) = 128,
//Ignore the length of the string and compare the results
NSWidthInsensitiveSearch NS_ENUM_AVAILABLE(10_5, 2_0) = 256,
//Ignore the case insensitive option and force the return of NSOrderedAscending or NSOrderedDescending
NSForcedOrderingSearch NS_ENUM_AVAILABLE(10_5, 2_0) = 512,
//Can only be applied to the rangeofstring:, stringbyreplaceingoccurrencesofstring: and replaceOccurrencesOfString: methods.
//Using a common and compatible comparison method,
//If this item is set, NSCaseInsensitiveSearch and NSAnchoredSearch can be removed
NSRegularExpressionSearch NS_ENUM_AVAILABLE(10_7, 3_2) = 1024
};
*/
NSComparisonResult result1 = [str1 compare:str3 options:NSCaseInsensitiveSearch];
if (result1 == 0)
{
NSLog(@"%@,%@ is equal if ignore capitalized",str1,str3);
}else
{
NSLog(@"%@,%@ is not equal if ignore capitalized",str1,str3);
}
//a,A is equal if ignore capitalized
Prefix in string
//- (BOOL)hasPrefix:(NSString *)str;
NSString *url = @"http://www.youdao.com/";
if ([url hasPrefix:@"http://"])
{
NSLog(@"the url has prefix 'http://'");
}else
{
NSLog(@"the url is not has prefix 'http://'");
}
//the url has prefix 'http://'
//**Note: prefix starts at location = 0
Suffix in string
NSString *imgName = @"image.png.jpg";
NSString *suffix = @".png";
if ([imgName hasSuffix:suffix])
{
NSLog(@"the imageName is end in .png");
}else
{
NSLog(@"the imageName is not end in .png");
}
//the imageName is not end in .png
String contains other characters or strings
NSString *strSource = @"abcde";
NSString *strFind1 = @"c";
NSString *strFind2 = @"ce";
NSRange range1 = [strSource rangeOfString:strFind1];
NSRange range2 = [strSource rangeOfString:strFind2];
//If strFind1 is not found, range.location = NSNotFound is returned
if (range1.location != NSNotFound)
{
NSLog(@"string '%@' is in the %ld position of the string '%@', and its length is %ld.",strFind1,range1.location,strSource,range1.length);
}else
{
NSLog(@"the string '%@' exclude string '%@'.",strSource,strFind1);
}
//string 'c' is in the 2 position of the string 'abcde', and its length is 1.
if (range2.location != NSNotFound)
{
NSLog(@"string '%@' is in the %ld position of the string '%@', and its length is %ld.",strFind1,range1.location,strSource,range1.length);
}else
{
NSLog(@"the string '%@' exclude string '%@'.",strSource,strFind2);
}
//the string 'abcde' exclude string 'ce'.
String truncation
NSString *str = @"0123456789";
/*
- (NSString *)substringFromIndex:(NSUInteger)from;
Start at subscript x and intercept to subscript str.length - 1 [x,str.length - 1]
*/
NSString *strSubFrom = [str substringFromIndex:3];
NSLog(@"%@",strSubFrom); //3456789
/*
- (NSString *)substringToIndex:(NSUInteger)to;
Intercept from subscript 0 to subscript x (excluding x) [0,x)
*/
NSString *strSubTo = [str substringToIndex:3];
NSLog(@"%@",strSubTo); //012
/*
- (NSString *)substringWithRange:(NSRange)range;
Starting from subscript x, intercept length is y
*/
NSString *strRange = [str substringWithRange:NSMakeRange(1, 2)];
NSLog(@"%@",strRange); //12
Letter case
NSString *strLetter = @"abcDeFg";
NSLog(@"%@",[strLetter uppercaseString]); //ABCDEFG
NSLog(@"%@",[strLetter lowercaseString]); //abcdefg
NSLog(@"%@",[strLetter capitalizedString]); //Abcdefg
NSMutableString using
Create NSMutableString
/*
+ (NSMutableString *)stringWithCapacity:(NSUInteger)capacity;
This capacity is just a suggestion for NSMutableString, which can exceed its size
The size of the string is not limited to the capacity provided, which is only an optimal value
*/
NSMutableString *str = [NSMutableString stringWithCapacity:42];
Append string
NSMutableString *string = [[NSMutableString alloc] init];
[string appendString:@"Hello there "];
NSLog(@"%@",string); //Hello there
[string appendFormat:@"human %d!",39];
NSLog(@"%@",string); //Hello there human 39!
Insert string
NSMutableString *str = [NSMutableString stringWithString:@"1245"];
[str insertString:@"3" atIndex:2];
NSLog(@"%@",str); //12345
Delete string
NSMutableString *string1 = [NSMutableString stringWithString:@"abcdefg"];
NSRange rangeNum = [string1 rangeOfString:@"de"];
//If rangeNum.location == NSNotFound, the program will crash
if (rangeNum.location != NSNotFound)
{
[string1 deleteCharactersInRange:rangeNum];
NSLog(@"%@",string1); //abcfg
}
Replace string
NSMutableString *str = [NSMutableString stringWithString:@"1245"];
[str replaceCharactersInRange:NSMakeRange(1, 2) withString:@"98"];
NSLog(@"%@",str); //1985