How to extract string from string - objective-c

how to store Height Value separately "6ft 7inch"
6ft in one string and 7inch in another string.
6 and 7 will be dynamically changes ft inch will be constant.

I assume there will always be a single space character separating the 2 height values that you want to extract. You can use -componentsSeparatedByString method to turn the string into array of strings separated by the space character
NSString *originalString = #"6ft 7inch";
NSArray *separatedStrings = [originalString componentsSeparatedByString:#" "];
NSString *feetString = separatedStrings[0];
NSString *inchString = separatedStrings[1];
If there could be cases where there are no spaces in between you'll have to find the index of the key character set and then create substrings using them. Let me know if you need to know how

You just need to split the string.
NSString *combineString=#"6ft 7inch";
NSArray *stringsArray=[combineString componentsSeparatedByString:#" "];
if ([stringsArray count ]> 0) {
//here is the ft string
NSString *ftString=[stringsArray objectAtIndex:0];
if ([stringsArray count ]> 1)
{
//here is the inch string
NSString *inchString=[stringsArray objectAtIndex:1];
}
else
{
NSLog(#"Inch value not found");
}
}
else
{
NSLog(#"Empty String");
}

There are many ways to accomplish that. However, in your case it is the easiest way, so separate the string at the space:
NSString *string = #"6ft 7inch";
NSArray *components = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet];

Related

Check if it is possible to break a string into chunks?

I have this code who chunks a string existing inside a NSString into a NSMutableArray:
NSString *string = #"one/two/tree";
NSMutableArray *parts = [[string componentsSeparatedByString:#"/"] mutableCopy];
NSLog(#"%#-%#-%#",parts[0],parts[1],parts[2]);
This command works perfectly but if the NSString is not obeying this pattern (not have the symbol '/' within the string), the app will crash.
How can I check if it is possible to break the NSString, preventing the app does not crash?
Just check parts.count if you don't have / in your string (or only one), you won't get three elements.
NSString *string = #"one/two/tree";
NSMutableArray *parts = [[string componentsSeparatedByString:#"/"] mutableCopy];
if(parts.count >= 3) {
NSLog(#"%#-%#-%#",parts[0],parts[1],parts[2]);
}
else {
NSLog(#"Not found");
}
From the docs:
If list has no separators—for example, "Karin"—the array contains the string itself, in this case { #"Karin" }.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:
You might be better off using the "opposite" function to put it back together...
NSString *string = #"one/two/three";
NSArray *parts = [string componentsSeparatedByString:#"/"];
NSString *newString = [parts componentsJoinedByString:#"-"];
// newString = #"one-two-three"
This will take the original string. Split it apart and then put it back together no matter how many parts there are.

split NSString using componentsSeparatedByString

I have a string I need to split. It would be easy using componentsSeparatedByString but my problem is that the separator is a comma but I could have commas that aren't separator.
I explain:
My string:
NSString *str = #"black,red, blue,yellow";
the comma between red and blue must not be considered as separator.
I can determine if comma is a separator or not checking if after it there is a white space.
The goal is to obtain an array with:
(
black,
"red, blue",
yellow
)
This is tricky. First replace all occurences of ', ' (comma+space) with say '|' then use components separated method. Once you are done, again replace '|' with ', ' (comma+space).
Just to complete the picture, a solution that uses a regular expression to directly identify commas not followed by white space, as you explain in your question.
As others have suggested, use this pattern to substitute with a temporary separator string and split by that.
NSString *pattern = #",(?!\\s)"; // Match a comma not followed by white space.
NSString *tempSeparator = #"SomeTempSeparatorString"; // You can also just use "|", as long as you are sure it is not in your input.
// Now replace the single commas but not the ones you want to keep
NSString *cleanedStr = [str stringByReplacingOccurrencesOfString: pattern
withString: tempSeparator
options: NSRegularExpressionSearch
range: NSMakeRange(0, str.length)];
// Now all that is needed is to split the string
NSArray *result = [cleanedStr componentsSeparatedByString: tempSeparator];
If you are not familiar with the regex pattern used, the (?!\\s) is a negative lookahead, which you can find explained quite well, for instance here.
Here is coding implementation for cronyneaus4u's solution:
NSString *str = #"black,red, blue,yellow";
str = [str stringByReplacingOccurrencesOfString:#", " withString:#"|"];
NSArray *wordArray = [str componentsSeparatedByString:#","];
NSMutableArray *finalArray = [NSMutableArray array];
for (NSString *str in wordArray)
{
str = [str stringByReplacingOccurrencesOfString:#"|" withString:#", "];
[finalArray addObject:str];
}
NSLog(#"finalArray = %#", finalArray);
NSString *str = #"black,red, blue,yellow";
NSArray *array = [str componentsSeparatedByString:#","];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (int i=0; i < [array count]; i++) {
NSString *str1 = [array objectAtIndex:i];
if ([[str1 substringToIndex:1] isEqualToString:#" "]) {
NSString *str2 = [finalArray objectAtIndex:(i-1)];
str2 = [NSString stringWithFormat:#"%#,%#",str2,str1];
[finalArray replaceObjectAtIndex:(i-1) withObject:str2];
}
else {
[finalArray addObject:str1];
}
}
NSLog(#"final array count : %d description : %#",[finalArray count],[finalArray description]);
Output:
final array count : 3 description : (
black,
"red, blue",
yellow
)

Objective-C NSString character substitution

I have a NSString category I am working on to perform character substitution similar to PHP's strtr. This method takes a string and replaces every occurrence of each character in fromString and replaces it with the character in toString with the same index. I have a working method but it is not very performant and would like to make it quicker and able to handle megabytes of data.
Edit (for clarity):
stringByReplacingOccurrencesOfString:withString:options:range: will not work. I have to take a string like "ABC" and after replacing "A" with "B" and "B" with "A" end up with "BAC". Successive invocations of stringByReplacingOccurrencesOfString:withString:options:range: would make a string like "AAC" which would be incorrect.
Suggestions would be great, sample code would be even better!
Code:
- (NSString *)stringBySubstitutingCharactersFromString:(NSString *)fromString
toString:(NSString *)toString;
{
NSMutableString *substitutedString = [self mutableCopy];
NSString *aCharacterString;
NSUInteger characterIndex
, stringLength = substitutedString.length;
for (NSUInteger i = 0; i < stringLength; ++i) {
aCharacterString = [NSString stringWithFormat: #"%C", [substitutedString characterAtIndex:i]];
characterIndex = [fromString rangeOfString:aCharacterString].location;
if (characterIndex == NSNotFound) continue;
[substitutedString replaceCharactersInRange:NSMakeRange(i, 1)
withString:[NSString stringWithFormat:#"%C", [toString characterAtIndex:characterIndex]]];
}
return substitutedString;
}
Also this code is executed after every change to text in a text view. It is passed the entire string every time. I know that there is a better way to do it, but I do not know how. Any suggestions for this would be most certainly appreciated!
You can make that kind of string substitution with NSRegularExpression either modifying an mutable string or creating a new immutable string. It will work with any two strings to substitute (even if they are more than one symbol) but you will need to escape any character that means something in a regular expression (like \ [ ( . * ? + etc).
The pattern finds either of the two substrings with the optional "anything" between and than replaces them with the two substrings with each other preserving the optional string between them.
// These string can be of any length
NSString *firstString = #"Axa";
NSString *secondString = #"By";
// Escaping of characters used in regular expressions has NOT been done here
NSString *pattern = [NSString stringWithFormat:#"(%#|%#)(.*?)(%#|%#)", firstString, secondString, firstString, secondString];
NSString *string = #"AxaByCAxaCBy";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:&error];
if (error) {
// Insert error handling here...
}
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#"$3$2$1"];
NSLog(#"Before:\t%#", string); // AxaByCAxaCBy
NSLog(#"After: \t%#", modifiedString); // ByAxaCByCAxa

How to remove a section of a string using escape character

I have a set of NSString representing the names of the files in a directory. These names are structured this way:
XXXXXXXXX_YYYY_AAAA.ext
All the sections separated by "_" are of variable length and I would only have the first.
How can I separate the first part from the other?
Find the position of the '_' character, then get a substring 0 through that position. Note that substringToIndex: does not include the character at the index position.
NSRange r = [myString rangeOfString:#"_"];
NSString *res = [myString substringToIndex:r.location];
Take a look at the NSString method componentsSeparatedByString:. That will tokenize a string and return you an array. Something like this:
NSArray *array = [#"XXXXXXXXX_YYYY_AAAA.ext" componentsSeparatedByString:#"_"];
NSString *firstToken = [array objectAtIndex:0];
NSArray *array = [yourString componentsSeparatedByString:#"_"];
NSString *Xs = [array objectAtIndex:0];
Try componentsSeparatedByString: under the heading Dividing Strings.
NSString Docs

Remove last character of NSString

I've got some trouble 'ere trying to remove the last character of an NSString.
I'm kinda newbie in Objective-C and I have no idea how to make this work.
Could you guys light me up?
NSString *newString = [oldString substringToIndex:[oldString length]-1];
Always refer to the documentation:
substringToIndex:
length
To include code relevant to your case:
NSString *str = textField.text;
NSString *truncatedString = [str substringToIndex:[str length]-1];
Try this:
s = [s substringToIndex:[s length] - 1];
NSString *string = [NSString stringWithString:#"ABCDEF"];
NSString *newString = [string substringToIndex:[string length]-1];
NSLog(#"%#",newString);
You can see = ABCDE
NSString = *string = #"abcdef";
string = [string substringToIndex:string.length-(string.length>0)];
If there is a character to delete (i.e. the length of the string is greater than 0)
(string.length>0) returns 1, thus making the code return:
string = [string substringToIndex:string.length-1];
If there is NOT a character to delete (i.e. the length of the string is NOT greater than 0)
(string.length>0) returns 0, thus making the code return:
string = [string substringToIndex:string.length-0];
which prevents crashes.
This code will just return the last character of the string and not removing it :
NSString *newString = [oldString substringToIndex:[oldString length]-1];
you may use this instead to remove the last character and retain the remaining values of a string :
str = [str substringWithRange:NSMakeRange(0,[str length] - 1)];
and also using substringToIndex to a NSString with 0 length will result to crashes.
you should add validation before doing so, like this :
if ([str length] > 0) {
str = [str substringToIndex:[s length] - 1];
}
with this, it is safe to use substring method.
NOTE : Apple will reject your application if it is vulnerable to crashes.
Simple and Best Approach
[mutableString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];