Add items from Array with sign $ - objective-c

I have an Array , if I print that in console it shows
Price Array=(
"$100",
"$300"
)
I need to add add objects at each index and show it in label. Please suggest any idea, in this case how it will show 400 with $ sign?
I tried this in view did load
for (int j=0; j<[cartArray2 count]; j++)
{
itemPrize =[prizelabel.text floatValue];
tempVar=itemPrize;
total=total+tempVar;
NSString *strTotalAmt = [NSString stringWithFormat:#"%f",total];
prizelabel.text=strTotalAmt;
}
NSLog( #"Toatl= %f",total);`
where in interface float itemPrize,tempVar,total
This is what i did
for (int j=0; j<[cartArray2 count]; j++)
{
NSMutableString *cleanedText = [NSMutableString stringWithCapacity:0];
NSString *newRecord = [[cartArray2 objectAtIndex:j] stringByReplacingOccurrencesOfString:#"$" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [[cartArray2 objectAtIndex:j] length])];
[cleanedText appendFormat:#"%#\n", newRecord];
NSLog(#"Cleaned=%#", cleanedText);
itemPrize =[cleanedText intValue];
tempVar=itemPrize;
total=total+tempVar;
NSString *strTotalAmt = [NSString stringWithFormat:#"%d",total];
prizelabel.text=strTotalAmt;
}
NSLog( #"Toatl= %d",total);

To get rid of $ sign you should try: [[itemPrize componentsSeparatedByString:#"$"] objectAtIndex:1];. Then you should use stringWithFormat method to do the string formatting.

Related

How to compare unichar from a buffer?

I'm trying to compare unichar, but my code below doesn't work.
NSString *str = #"some string ^ ^";
NSUInteger len = [str length];
unichar buffer[len+1];
[str getCharacters:buffer range:NSMakeRange(0, len)];
for(int i = 0; i < len; i++) {
if (buffer[i] == '^') NSLog(#"%C", buffer[i]);
}
It doesn't seem to be able to log the ^ even though it exist. Any idea why?

NSScanner only working with non-initialized variables. Why?

The following code works, but produces warnings about non-initialized variables.
The code parses a string representing a molecule, such as #"2C12;5H1;1O16". It checks that it is correctly formatted and that all the components are valid isotopes. As listed, it works perfectly, but produces warnings from the compiler.
//listOfNames is a global variable, an NSArray containing strings of all isotope names i.e. #"Na23"
-(bool)canGrokSpeciesName:(NSString*)theSpeciesName{
//Test that the species name makes sense
//Names should be of the form of repeated #"nnSSaa" with nn being the multiplier, SS being the element name, aa being the atomic mass number
bool couldGrok = [theSpeciesName isNotEqualTo:#""];
if(couldGrok){
NSArray* listOfAtomsWithMultiplier = [theSpeciesName componentsSeparatedByString:#";"];
for (int i=0; i<[listOfAtomsWithMultiplier count]; i++) NSLog(#"%#", [listOfAtomsWithMultiplier objectAtIndex:i]);
NSInteger multiplet[ [listOfAtomsWithMultiplier count] ];
bool ok[ [listOfAtomsWithMultiplier count] ];
bool noFail = true;
for (int i=0; i<[listOfAtomsWithMultiplier count]; i++) {
NSScanner* theScanner = [NSScanner scannerWithString:[listOfAtomsWithMultiplier objectAtIndex:i]];
NSString* multipletString;
if(![theScanner isAtEnd]) [theScanner scanUpToCharactersFromSet:[NSCharacterSet letterCharacterSet] intoString:&multipletString];
multiplet[i] = [multipletString integerValue];
NSString* atomString;
if(![theScanner isAtEnd]) [theScanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&atomString];
NSInteger A;
if(![theScanner isAtEnd]) [theScanner scanInteger:&A];
NSLog(#"%#%i with multiplet of %i", atomString, (int)A, (int)multiplet[i]);
bool hasBeenFound = false;
for(int j=0; j<[listOfNames count]; j++){
if(noFail) hasBeenFound = hasBeenFound || [[listOfNames objectAtIndex:j] isEqualToString:[NSString stringWithFormat:#"%#%i", atomString, (int)A]];
}
couldGrok = couldGrok && noFail && hasBeenFound;
}
}
return couldGrok;
}
However, if I initialize with
NSString* multipletString = #"";
NSString* atomString = #"";
NSInteger A = -1;
then the NSScanner returns them with their originally initialized values. Am I missing something basic?
I prefer not to ignore warnings from the compiler, but following the compiler suggestions breaks the code. So, I suppose this is more a request for basic information than a request for how to fix my code. Thanks!

Search an NSMutableArray with strings if string is equal to other string NLog position of item

I have an NSMutableArray with items in it.
I would like to compare every item with a string.
If the string is the same then the next item of the array should be stored in another array.
NSString *string2 = [NSString stringWithFormat:#"Period:"];
// Filtern nach Periode
NSMutableArray *Eventarray =[NSMutableArray array];
for(int i=0;i<[lines count]; i++)
{
NSMutableString *string1 = [NSMutableString stringWithFormat: #"%#",[[lines objectAtIndex:i]description]];
// NSLog(#"%#",string1);
int index = [[lines objectAtIndex:i] indexOfObject:#"Period:"];
NSLog(#"%#",index);
if ([[lines objectAtIndex:i] isEqualToString:#"Period:"])
{
//strings are same
NSLog(#"ii");
NSLog(#"ii");
int e=i+1;
NSMutableString *Periode = [NSMutableString stringWithFormat: #"%#",[lines objectAtIndex:e]];
[Eventarray addObject:Periode];
}
[string1 deleteCharactersInRange:NSMakeRange([string1 length]-1, 1)];
}
for(int i=0;i<[Eventarray count]; i++)
{
NSLog(#"Eventarray: %#", [Eventarray objectAtIndex:i]);
}
The array looks like this:
2013-08-12 13:31:35.375 xxxx[3809:207] PublishedRoster
2013-08-12 13:31:35.376 xxxx[3809:207] Period:
2013-08-12 13:31:35.377 xxxx[3809:207] 25Jul2013-08Sep2013
I tried everything but I don't know whats wrong. What am I missing?
Try using NSRange
If you want to search for a substring
NSString *homebrew = #"Rajneesh071";
NSRange range = [homebrew rangeOfString:#"Raj"];
// Did we find the string "Raj" ?
if (range.length > 0)
NSLog(#"Range is: %#", NSStringFromRange(range));
In your code you can do it like.
for(int i=0;i<[lines count]; i++)
{
NSRange stringRange = [[lines objectAtIndex:i] rangeOfString:#"Period:" options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound)
{
[Eventarray addObject:Periode];
}
}

How to print the reverse of NSString in objective c without using componentsSeparatedByString method?

I want to make a method which gives reverse of string.suppose I pass a NSString "Welcome to Objective C" in method and that method return a reverse of string like "C Objective to Welcome" not "C evitcejbO ot emocleW" without the use of componentsSeparatedByString method.
Is it possible to do with Objective c..?
Please help.
You can enumerate strings by words.
NSString *string = #"Welcome to Objective-C!";
NSMutableArray *words = [NSMutableArray array];
[string enumerateLinguisticTagsInRange:NSMakeRange(0, [string length])
scheme:NSLinguisticTagSchemeTokenType
options:0
orthography:nil
usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {
[array addObject:[string substringWithRange:tokenRange]];
}];
NSMutableString *reverseString = [[NSMutableString alloc] init];
for (NSString *word in [words reverseObjectEnumerator]){
[reverse appendString:word];
}
NSLog(#"%#", reverseString);
This will print...
"!C-Objective to Welcome"
You can change the options to omit whitespaces and stuff...
I used below method for reversing string in iOS
- (NSString *)reverseString:(NSString *)stringToReverse
{
NSMutableString *reversedString = [NSMutableString stringWithCapacity:[stringToReverse length]];
[stringToReverse enumerateSubstringsInRange:NSMakeRange(0, [stringToReverse length])
options:(NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences)
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[reversedString appendString:substring];
}];
return reversedString;
}
Sorry I misread your question earlier. I did it using a series of loops, my answer is messier than Fogmeister but I wanted to give it a shot to see if I could do it.
NSString *str = #"This is a test";
NSMutableArray *array = [[NSMutableArray alloc] init];
for(int i = 0; i < [str length]; i++)
{
char sTest = [str characterAtIndex:i];
if(sTest == ' ')
{
[array addObject:[NSNumber numberWithInt:i]];
}
}
NSInteger iNext = [[array objectAtIndex:[array count]-1] integerValue];
iNext+=1;
if(iNext < [str length])
{
[array addObject:[NSNumber numberWithInt:iNext]];
}
NSMutableArray *wordArray = [[NSMutableArray alloc] init];
for(int i = 0; i < [array count]; i++)
{
if (i == 0)
{
int num = [[array objectAtIndex:i] integerValue];
NSString *s = [[str substringFromIndex:0] substringToIndex:num];
[wordArray addObject:s];
}
else if(i == [array count]-1)
{
int prev = [[array objectAtIndex:i-1] integerValue]+1;
int num = [str length];
NSString *s = [[str substringToIndex:num] substringFromIndex:prev];
[wordArray addObject:s];
}
else
{
int prev = [[array objectAtIndex:i-1] integerValue]+1;
int num = [[array objectAtIndex:i] integerValue];
NSString *s = [[str substringToIndex:num] substringFromIndex:prev];
[wordArray addObject:s];
}
}
NSMutableArray *reverseArray = [[NSMutableArray alloc]init];
for(int i = [wordArray count]-1; i >= 0; i--)
{
[reverseArray addObject:[wordArray objectAtIndex:i]];
}
NSLog(#"%#", reverseArray);
Here i have done with replacing character with minimal number of looping. log(n/2).
NSString *string=#"Happy World";
NSInteger lenth=[string length];
NSInteger halfLength=[string length]/2;
for(int i=0;i<halfLength;i++)
{
NSString *leftString=[NSString stringWithFormat:#"%c",[string characterAtIndex:i]];
NSString *rightString=[NSString stringWithFormat:#"%c",[string characterAtIndex:(lenth-i-1)]];
string= [string stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:rightString];
string=[string stringByReplacingCharactersInRange:NSMakeRange((lenth-i-1), 1) withString:leftString];
}
NSLog(#"%#",string);
Try This , It's working perfect as per your expectation ,
Call Function :-
[self reversedString:#"iOS"];
Revers String Function :-
-(void)reversedString :(NSString *)reversStr
{ // reversStr is "iOS"
NSMutableString *reversedString = [NSMutableString string];
NSInteger charIndex = [reversStr length];
while (charIndex > 0) {
charIndex--;
NSRange subStrRange = NSMakeRange(charIndex, 1);
[reversedString appendString:[reversStr substringWithRange:subStrRange]];
}
NSLog(#"%#", reversedString); // outputs "SOi"
}
Hope So this is help for some one .
There is no API to do that, if that's what you are asking.
You can always iterate through the string looking for white spaces (or punctuation, it depends on your needs), identify the words and recompose your "reversed" message manually.

Displaying an array in xcode

I am trying to display the an array with different factors of a number ("prime"). But instead of giving me the int numbers I always get 0,1,2,3,4,5,... .
factors.text = #"";
int factorsNumber;
NSMutableArray *array;
array = [NSMutableArray arrayWithCapacity:5];
for (factorsNumber=1; factorsNumber<=prime; factorsNumber++) {
if (prime%factorsNumber == 0) {
[array addObject:[NSString stringWithFormat:#"%d", factorsNumber]];
}
}
for (int i = 0; i < [array count]; i++) {
[array replaceObjectAtIndex:1 withObject:#"4"];
NSString *temp = [NSString stringWithFormat:#"%d, ", i, [[array objectAtIndex:i] intValue]];
factors.text = [factors.text stringByAppendingString:temp];
}
Replace
NSString *temp = [NSString stringWithFormat:#"%d, ", i, [[array objectAtIndex:i] intValue]];
with
NSString *temp = [NSString stringWithFormat:#"%d, ", [[array objectAtIndex:i] intValue]];
The problem was you were only printing the array index, not the value.