For example my string is NSString *str=#"appleIsTheBest". Remember that the code have to work with any strings, not just with this.
NSString *str = #"appleIsTheBest";
str = [str substringWithRange:NSMakeRange(5, str.length - 5 - 3)];
Of course, you'll need to check the string's length before sending the substringWithRange: message.
Related
I have the following code:
return (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(";:#&=+$,/?%#[]"), kCFStringEncodingUTF8);
Xcode says it is deprecated in iOS 9. So, how do I use stringByAddingPercentEncodingWithAllowedCharacters ?
Thanks!
try this
NSString *value = #"<url>";
value = [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
The character set URLQueryAllowedCharacterSet contains all characters allowed in the query part of the URL (..?key1=value1&key2=value2) and is not limited to characters allowed in keys and values of such a query. E.g. URLQueryAllowedCharacterSet contains & and +, as these are of course allowed in query (& separates the key/value pairs and + means space), but they are not allowed in a key or a value of such a query.
Consider this code:
NSString * key = "my&name";
NSString * value = "test+test";
NSString * safeKey= [key
stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet URLQueryAllowedCharacterSet]
];
NSString * safeValue= [value
stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet URLQueryAllowedCharacterSet]
];
NSString * query = [NSString stringWithFormat:#"?%#=%#", safeKey, safeValue];
query will be ?my&name=test+test, which is totally wrong. It defines a key named my that has no value and a key named name whose value is test test (+ means space!).
The correct query would have been ?my%26name=test%2Btest.
As long as you only deal with ASCII strings or as long as the server can deal with UTF-8 characters in the URL (most web servers today do that), the number of chars you absolutely have to encode is actually rather small and very constant. Just try that code:
NSCharacterSet * queryKVSet = [NSCharacterSet
characterSetWithCharactersInString:#":/?&=;+!##$()',*% "
].invertedSet;
NSString * value = ...;
NSString * valueSafe = [value
stringByAddingPercentEncodingWithAllowedCharacters:queryKVSet
];
Another solution to encode those characters allowed in URLQueryAllowedCharacterSet but not allowed in a key or a value (e.g.: +):
- (NSString *)encodeByAddingPercentEscapes {
NSMutableCharacterSet *charset = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[charset removeCharactersInString:#"!*'();:#&=+$,/?%#[]"];
NSString *encodedValue = [self stringByAddingPercentEncodingWithAllowedCharacters:charset];
return encodedValue;
}
I am making a calculator and unable to seperate the input string in corrosponding to operands.
For example : 2*5 - 6 +8/2. I want an array with components 2, 5, 6, 8, 2 so that I can store the oprators also and then sort accordingly. Please help
NSString *str=#"2*5 - 6 +8/2"; // assume that this is your str
// here remove the white space
str =[str stringByReplacingOccurrencesOfString:#" " withString:#""];
// here remove the all special characters in NSString
NSCharacterSet *noneedstr = [NSCharacterSet characterSetWithCharactersInString:#"*/-+."];
str = [[str componentsSeparatedByCharactersInSet: noneedstr] componentsJoinedByString:#","];
NSLog(#"the str=-=%#",str);
the out put is
the str=-=2,5,6,8,2
You can use the method, componentsSeparatedByCharactersInSet:.
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"*-+/"];
NSArray *numbers = [text componentsSeparatedByCharactersInSet:set];
You can get arrays of the operands and operators like so. This assumes the expression is valid, base 10, begins and ends with operands, etc. The expression would then be operands[0], operators[0], operands[1], operators[1], and so on.
NSString *expression = #"2*5 - 6 +8/2";
// Could use a custom character set as well, or -whitespaceAndNewlineCharacterSet
NSCharacterSet *whitespaceCharacterSet = [NSCharacterSet whitespaceCharacterSet];
NSArray *nonWhitespaceComponents = [expression componentsSeparatedByCharactersInSet:whitespaceCharacterSet];
NSString *trimmedExpression = [nonWhitespaceComponents componentsJoinedByString:#""];
// To get an array of the operands:
NSCharacterSet *operatorCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"+-/*"];
NSArray *operands = [trimmedExpression componentsSeparatedByCharactersInSet:operatorCharacterSet];
// To get the array of operators:
NSCharacterSet *baseTenCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
NSArray *operators = [trimmedExpression componentsSeparatedByCharactersInSet:baseTenCharacterSet];
// Since expression should begin and end with operands, first and last strings will be empty
NSMutableArray *mutableOperators = [operators mutableCopy];
[mutableOperators removeObject:#""];
operators = [NSArray arrayWithArray:mutableOperators];
NSLog(#"%#", operands);
NSLog(#"%#", operators);
I have a number which will be represented as string. It is longer than 4 chars. I need to create new string from 5th till the end for that number.
For example if I have 56789623, I need to have 9623 as a result (5678 | 9623).
How to do that?
P.S. I suppose that this is very simple question, but I don't know how properly ask Google about that.
NSString *str = #"56789623";
NSString *first, *second;
if ([str length] > 4) {
first = [str substringWithRange:NSMakeRange(0, 4)];
second = [str substringWithRange:NSMakeRange(4, [str length] - 4)];
} else {
first = str;
second = nil;
}
Use this Simple functions
- (NSString *)substringFromIndex:(NSUInteger)from;
- (NSString *)substringToIndex:(NSUInteger)to;
- (NSString *)substringWithRange:(NSRange)range;
You can use:
- (NSString *)substringFromIndex:(NSUInteger)anIndex
NSString *number = #"56789623";
NSString *result = [number substringFromIndex:4];
NSLog(#"%#", result);
result contains the string: #"9623"
The keywords you were looking for are: substring and range. There are several ways to use them. Example code split string into 2 equal (if number of characters is even almost equal) substrings:
NSString *str = #"56789623";
NSInteger middleIndex = (NSInteger)(str.length/2);
NSString *strFirstPart = [str substringToIndex:middleIndex];
NSString *strSecondPart = [str substringFromIndex:middleIndex];
NSString *strFirstPart2 = [str substringWithRange:NSMakeRange(0, middleIndex)];
NSString *strSecondPart2 = [str substringWithRange:NSMakeRange(middleIndex, [str length]-middleIndex)];
I have an NSString *fileName
This will contain a variable number from 1 to 3 digits. I want to extract all of the digits
I can get the first digit using
//create text for appliance identifier
char obsNumber = [fileName characterAtIndex:3];//get 4 character
NSLog(#"Obs number %c",obsNumber);
//Text label
[cell.titleLabel setText:[NSString stringWithFormat:#"Item No: %c",obsNumber]];
NSLog(#"Label for observation = %#",cell.titleLabel.text);
However if the string contains the number for example 78, or 204 I want to catch all two or three digits.
I tried this
//create text for appliance identifier
char obsNumber1 = [fileName characterAtIndex:3];//get 4 character
char obsNumber2 = [fileName characterAtIndex:4];//get 5 character
char obsNumber3 = [fileName characterAtIndex:5];//get 6 character
NSLog(#"Obs number %c,%c,%c",obsNumber1,obsNumber2,obsNumber3);
//Text label
[cell.titleLabel setText:[NSString stringWithFormat:#"Item No: %c,%c,%c",obsNumber1,obsNumber2,obsNumber3]];
NSLog(#"Label for observation = %#",cell.titleLabel.text);
This gave me 18c 1ce etc
Would this work for you?
NSString *filename = #"obs127observation"; //An example variable with your format
This code could be tidier but you should get the idea:
NSString *filenameNumber = [[filename
stringByReplacingOccurrencesOfString:#"observation"
withString:#""]
stringByReplacingOccurrencesOfString:#"obs"
withString:#""];
you can trim other letters except the decimals.
NSString *onlyNumbers=[yourstring stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
As your comment says , It has predefined set of values, right. Then try like this
NSstring *str = [filename substringFromIndex:11];
// Convert the str to char[]
Then you should try with the NSScanner :
NSString *numberString;
NSScanner *scanner = [NSScanner scannerWithString:filename];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
// Throw away characters before the first number.
[scanner scanUpToCharactersFromSet:numbers intoString:NULL];
// Collect numbers.
[scanner scanCharactersFromSet:numbers intoString:&numberString];
// Result.
int number = [numberString integerValue];
// you can play around with the set of number
Your approach of separating one character at a time and then combining them back into a string is an awkward, overly complex way of going about this. Kumar's suggestion of using NSScanner is a good option if you have a number in the middle of a string.
However, you make it sound like your string will always contain a number and only a number. Is that true? Or will there be characters you need to ignore?
You need to define the problem clearly and completely before you can select the best solution.
It might be as simple as using the NSString method substringWithRange.
I have a NSString that has two characters.
The NSSring looks something like this
FW
I use this code to capture the first character
NSString *firstStateString = [totInstStateString substringToIndex:1];
this pecie of code returns F, I would like to know how to return the second character to its own string using substringToIndex.
anyhelp would be appreciated.
Use substringWithRange:
For Example :
[#"fw" substringWithRange:NSMakeRange(1, 1)];
will get you #"w"
have a look at the apple docs
Use following code .. My be helpful in your case.
NSString *myString = #"FFNNF";
for(int i = 0; i < [myString length]; i++)
{
NSLog(#"%#", [myString substringWithRange:NSMakeRange(i, 1)])
}
Also check This Question.
How to get a single NSString character from an NSString
The other option is:
NSString *lastStateString = [totInstStateString substringFromIndex:1];
This will get the last character of a two-character string. You might want to do some bounds checking somewhere in there.