Removing last characters of NSString until it hits a separator - ios

I've got a string that shows the stock amount using "-" as separators.
It's built up like this: localStock-wareHouseStock-supplierStock
Now I want to update the supplierStock at the end of the string, but as you can see in the code below it goes wrong when the original string returns more than a single-space value (such as 20).
Is there a way to remove all characters until the last "-" (or remove characters after the second "-")?
NSMutableString *string1 = [NSMutableString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *newString = [string1 substringToIndex:[string1 length]-2];
NSLog(#"newString: %#",newString);
NSString *colorStock = [NSString stringWithFormat:#"%#-%#",newString,p2.supplierStock];
NSLog(#"colorstock: %#",colorStock);
p1.colorStock = colorStock;
NSLog1
string1: 0-0-0
newString: 0-0
colorstock: 0-0-20
NSLog2
string1: 0-0-20
newString: 0-0-
colorstock: 0-0--20
EDIT: Got it working thanks to Srikar!
NSString *string1 = [NSString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *finalString = [string1 stringByReplacingOccurrencesOfString:[[string1 componentsSeparatedByString:#"-"] lastObject] withString:p2.supplierStock.stringValue];
NSLog(#"finalString: %#",finalString);
p1.colorStock = finalString;

Why not use componentsSeparatedByString followed by lastObject ?
NSString *supplierStock = [[string1 componentsSeparatedByString:#"-"] lastObject];
The above works if the "stock amount" is always in sets of 3's separated by a "-". Also since you always want supplierStock, lastObject is perfect for your needs.
Of course after splitting string1 with - you get a NSArray instance and you can access the individual components using objectAtIndex:index. So if you want localStock you can get by
NSString *localStock = [[string1 componentsSeparatedByString:#"-"] objectAtIndex:0];

I would suggest splitting the string into the 3 parts using [NSString componentsSeparatedByString:#"-"] and then building it back up again:
NSArray *components = [p1.colorStock componentsSeparatedByString:#"-"];
p1.colorStock = [NSString stringWithFormat:#"%#-%#-%#",
[components objectAtIndex:0],
[components objectAtIndex:1],
p2.supplierStock];

With a string that looks like
NSString *myString = #"Hello-World";
you can separate it with the componentsSeparatedByString: method of the NSString object as
NSArray *myWords = [myString componentsSeparatedByString:#"-"];
The myWords - array will then contain the two NSString objects Hello and World.
To access the strings:
NSString *theHelloString = [myWords objectAtIndex:0];
NSString *theWorldString = [myWords objectAtIndex:1];
Hope it helps!

None of these examples show how to do this if you are unaware of how many of these separator occurrences you're going to have in the original string.
Here's what I believe the correct the correct code should be for dismantling the original string and rebuilding it until you reach the final separator, regardless of how many separators it contains.
NSString *seperator = #" ";
NSString *everythingBeforeLastSeperator;
NSArray *stringComponents = [originalString componentsSeparatedByString:seperator];
if (stringComponents.count!=0) {
everythingBeforeLastSeperator = [stringComponents objectAtIndex:0];
for (int a = 1 ; a < (stringComponents.count - 1) ; a++) {
everythingBeforeLastSeperator = [NSString stringWithFormat:#"%#%#%#", everythingBeforeLastSeperator, seperator, [stringComponents objectAtIndex:a]];
}
}
return everythingBeforeLastSeperator;

Related

Concatenate two strings with a backslash iOS

I am new to Objective-C and I need to have a string like "abc\123"
To have this I have tried doing:-
NSString *first = #"abc\\"; //Should escape
NSString *second= #"123";
NSString *combined= [NSString stringWithFormat:#"%#%#", first, second]; //which should give abc\123
But I get an output as "abc\\123".
I am really stuck on this one. Any help is appreciated
Backslash itself is the escape character so needs character to read ahead, you need to escape it.
This results same output you like.
NSString *first = #"abc\\";
You can check just by adding one more backshash #"abc\\\" gives you missing character "" runtime error.
NSString *first = #"abc\\"; // log results abc\
NSString *first = #"abc\\\\"; // log results abc\\
Can do by adding between format specifiers by following same backslash rule.
NSString *combined= [NSString stringWithFormat:#"%#\\%#", first, second];
It's the output issue, in fact, the string is correct.
let array = ["abc", "123"]
let separator = "\\"
separator.characters.count //count=1
let x = array.joined(separator: "\\")
x.characters.count //count = 7
You can use
stringByReplacingOccurrencesOfString:withString:
So in your case
NSString *first = #"abc\\"; //Should escape
NSString *second= #"123";
NSString *first = [first stringByReplacingOccurrencesOfString:#"\\" withString:#"\"];
NSString *combined= [NSString stringWithFormat:#"%#%#", first, second];
So your result will be abc\123

Extracting a substring in iOS

I have a string like this: "/Myapp/auth/hrHeadcount+ME+All IOU+Headcount+Grade" and I want to save only the "HeadCount" in another string. How can I do that?
NSString *srcStr = #"/Myapp/auth/hrHeadcount+ME+All IOU+Headcount+Grade";
NSString *dstStr = [[srcStr componentsSeparatedByString:#"+"] objectAtIndex:3];
If you are sure it will have same format then u can do the following
NSString *string1 = #"/Myapp/auth/hrHeadcount+ME+All IOU+Headcount+Grade";
NSArray *stringArray = [string1 componentsSeparatedByString:#"/"];
NSString *string2 = stringArray[3];
NSArray *finalArray = [string2 componentsSeparatedByString:#"+"];
NSString *finalString = finalArray[0];
final String will have the headCount u require

In objective-c how to get characters after n-th?

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)];

IOS NSString get characters before '#"

for example i have string like this:
NSString *one = B3#This is the first string
NSString *two = 1#This is the second string
How can i get the "B3" and "1" Character only (using objective C)
Thanks..
Turns out this is one way to do it:
NSRange range = [one rangeOfString:#"#" options:NSBackwardsSearch];
NSString *newString = [one substringToIndex:range.location];
Thanks for all the answers.
NSString* one = #"B3#";
NSString* two = #"1#";
NSString* result = [one stringByReplacingOccurrencesOfString:#"#" withString:#""];
NSString* result_2 = [two stringByReplacingOccurrencesOfString:#"#" withString:#""];
//if you need to marge
NSString* tot = [NSString stringWithFormat:#"%#%#",result,result_2];

I have a NSString like this: "Firstname Lastname". How do I convert it to "Firstname L."?

I would like to change it to first name and last initial.
Thanks!
NSString* nameStr = #"Firstname Lastname";
NSArray* firstLastStrings = [nameStr componentsSeparatedByString:#" "];
NSString* firstName = [firstLastStrings objectAtIndex:0];
NSString* lastName = [firstLastStrings objectAtIndex:1];
char lastInitialChar = [lastName characterAtIndex:0];
NSString* newNameStr = [NSString stringWithFormat:#"%# %c.", firstName, lastInitialChar];
This could be much more concise, but I wanted clarity for the OP :) Hence all the interim variables and var names.
This would do it:
NSArray *components = [fullname componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *firstnameAndLastnameInitial = [NSString stringWithFormat:#"%# %#.", [components objectAtIndex:0], [[components objectAtIndex:1] substringToIndex:1]];
This assumes that fullname is an instance of NSString and contains two components separated by whitespace, so you will need to check for that as well.
You can use this code snippet, first separate string using componentsSeparatedByString, then join them again but only get the first character of Lastname
NSString *str = #"Firstname Lastname";
NSArray *arr = [str componentsSeparatedByString:#" "];
NSString *newString = [NSString stringWithFormat:#"%# %#.", [arr objectAtIndex:0], [[arr objectAtIndex:1] substringToIndex:1]];
Get an array of the parts of the name individually:
NSString *sourceName = ...whatever...;
NSArray *nameComponents =
[sourceName
componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
Then, I guess:
NSString *compactName =
[NSString stringWithFormat:#"%# %#.",
[nameComponents objectAtIndex:0],
[[nameComponents lastObject] substringToIndex:1]];
That'll skip any middle names, though if there's only one name, like say 'Jeffry' then it'll output 'Jeffry J.'. If you pass in the empty string then it'll raise an exception when you attempt to get objectAtIndex:0 since that array will be empty. So you should check [nameComponents count].

Resources