I need to add space after every 4 characters in a string.. For example if the string is aaaaaaaa, i need to format it as aaaa aaaa. I tried the following code, but it doesn't work for me.
NSMutableString *currentFormattedString = [[NSMutableString alloc] initWithString:formattedString];
int count = [formattedString length];
for (int i = 0; i<count; i++) {
if ( i %4 == 0) {
[currentFormattedString insertString:#" " atIndex:i];
}
}
Can anyone help me with this?
You haven't said what isn't working with your code, so it's hard to know exactly what to answer. As a tip - in future questions don't just say "it isn't working", but state WHAT isn't working and HOW it isn't working. However...
NSMutableString *currentFormattedString = [[NSMutableString alloc] initWithString:formattedString];
int count = [formattedString length];
for (int i = 0; i<count; i++) {
if ( i %4 == 0) {
[currentFormattedString insertString:#" " atIndex:i];
}
}
You are inserting a space, but you are not then accounting for this in your index value. So, suppose your formattedString is aaaaaaaaaaaaaaaa
The first time through your loop, you will get to the 4th position and insert a space at i=4
aaaa aaaaaaaaaaaa
Now the next time you get to insert a space, i will be 8. But the 8th position in your currentFormattedString isn't where you think it will be
aaaa aaa aaaaaaaaa
Next time it will be another 4 characters along which still isn't where you think
aaaa aaa aa aaaaaaa
And so on
You have to take into account the inserted space which will affect the offset value.
NSString *text = [[NSString alloc] initWithString:#"aaaaaaaa"];
NSString *result = [[NSString alloc] init];
double count = text.length/4;
if (count>1) {
for (int i = 0; i<count; i++) {
result = [NSString stringWithFormat:#"%#%# ",result,[text substringWithRange:NSMakeRange(i*4, 4)]];
}
result = [NSString stringWithFormat:#"%#%# ",result,[text substringWithRange:NSMakeRange(((int)count)*4, text.length-((int)count)*4)]];
}
else result = text;
I found the following which formats a string to a telephone number format, but it looks like you could easily change it to support other formats
Telephone number string formatting
Nick Bull answered on the reasons why your method broke already.
IMHO the appropriate solution would be to use a while loop and do the loop increments yourself.
NSInteger i = 4; // first #" " should be inserted after the 4th (index = 3) char
while (i < count) {
[currentFormattedString insertString:#" " atIndex:i];
count ++; // you did insert #" " so the length of the string increased
i += 5; // you now must skip 5 (" 1234") characters
}
Related
I worked a lot in it and can't find a solution. Even the title can't explain clearly.
I have three values weight, quantity and total
I had done the following
float wq = [[weightarray objectAtIndex:selectedint]floatValue];
float q = [quantity floatValue];
float total = wq * q;
for ex, if
[weightarray objectAtIndex:selectedint] = #"3.14";
quantity = 4;
then the result is
wq = 3.140000 q= 4.000000 total = 12.560000
but I need
wq = 3.14 total = 12.56
what to do?
I searched a lot, someone suggests to use NSDecimal,
NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:FALSE raiseOnOverflow:TRUE raiseOnUnderflow:TRUE raiseOnDivideByZero:TRUE];
but the scale is not 2 here, wq value may have 3 or four numbers after point.
If the total = 2.30000100 means I need total = 2.300001
how to solve this?
I'm not entirely sure what it is your asking for, but it seems as if you want the values to only display a 2 d.p. In which case you could use a string format like so:
NSString *output = [NSString stringWithFormat:#"float = %.2f", 3.14];
The .2 specifies that the float should be justified to 2 d.p.
Hope this helps
There may be a more direct way to achieve it (which I don't know) but here's a suggestion...
Convert to string as you already do.
Use [myString hasSuffix:#"0"] to see if it ends in zero.
Use [myString substringToindex:[myString length]-1] to create a new string without the final zero.
Repeat.
I know it's not elegant, but unless someone has a better solution, this will at least do what you want.
UPDATE: scratch that - I just discovered [myString stringByTrimmingCharactersInSet:set]. Surely this must be what you need...?
Finally solution found, thanks to Martin
float total = 12.56000;
NSString *s = [NSString stringWithFormat:#"%f", total];
NSLog(#"%#",s);
BOOL success;
success =NO;
while(!success)
{
if ([s hasSuffix:#"0"])
{
s = [s substringWithRange:NSMakeRange(0,[s length]-1)];
}
else if ([s hasSuffix:#"."])
{
s = [s substringWithRange:NSMakeRange(0,[s length]-1)];
success = YES;
}
else
success = YES;
}
NSLog(#"%#",s);
if total = 12.560000 it returns total = 12.56
if total = 12.000000 it returns total = 12
if total = 10.000000 it returns total = 10
if total = 12.3000100 it returns total = 12.30001
hi i am getting the errer invalid operends to binary expression nsstring and id even i use typecasting this is the code in which i have problem . kindly correct this code.
for (int j = 0 ; j<newarray.count ; j++){
if(j<newarray.count){
message = (NSString *) message + [newarray objectAtIndex:j]+ "," ;
}
}
You can not use + operator with objects, for your specific case you may replace the whole cycle with:
NSString* message = [newarray componentsJoinedByString:#","];
And FIY Objective-C does not support operator overloading at all.
I'm not really sure if this was your intention, but if you were trying to append new information to the string separated by commas you could go with something like this:
for (int j = 0 ; j<newarray.count ; j++){
[message stringByAppendingString:[NSString stringWithFormat:#"%#,",[newarray objectAtIndex:j]]];
}
Additionally, your condition if(j<newarray.count) would always evaluate true in this loop, and is therefore unnecessary.
You seem to be assuming NSString acts like std::string in C++. Try this:
NSMutableString *message = ...;
for (unsigned j = 0; j < newarray.count; j++)
{
if (j > 0)
[message appendString:#", "];
[message appendString:[newarray objectAtIndex:j]];
}
You should cast "[newarray objectAtIndex:j]", whose default return type is "id"
Check this
Also IIRC NSString doesn't have + operand overloaded. So maybe you should try [NSString stringWithFormat:].
I want to convert decimal number in binary number. I'm using this method:
- (NSMutableString*)intStringToBinary:(long long)element{
NSMutableString *str = [[NSMutableString alloc] initWithString:#""];
for(NSInteger numberCopy = element; numberCopy > 0; numberCopy >>= 1)
{
[str insertString:((numberCopy & 1) ? #"1" : #"0") atIndex:0];
}
return str;
}
everything is going fine if the number "element" is >0. If the number is <0 there is the problem. For examle the method can't convert the number "-1". What can i do to solve the problem? Thanks in advance!!
You need an extra bit for the sign.
Example:
1xxxx represents the binary number + xxxx.
0yyyy represents the binary number - yyyy.
Here is a way to do it in Python using Wallar's Algorithm. The input and output are lists.
from math import *
def baseExpansion(n,c,b):
j = 0
base10 = sum([pow(c,len(n)-k-1)*n[k] for k in range(0,len(n))])
while floor(base10/pow(b,j)) != 0: j = j+1
return [floor(base10/pow(b,j-p)) % b for p in range(1,j+1)]
I'm trying to find the new line and returns that are inside an nsdata object that I'm parsing . Here's some code:
uint8_t *arr = [receivedData bytes];
NSUInteger begin1 = 0;
NSUInteger end1 = len;
uint8_t *arr1 = (Byte *)malloc(sizeof(Byte)*((end1-begin1+1)));
int j = 0;
for (int i = begin1; i < end1; i++){
arr1[j] = arr[i];
j++;
if (arr[i] == 10) NSLog(#"---new line code---"); //edit: working - data was a problem
}
I just need to know when I hit a new line or return.
Thank You.
That certainly looks correct. Are you certain that the data you're parsing has newlines? Could it be a /r instead of a /n? If you can, try using the debugger and step through to see what the values actually are, and compare with what you expect them to be, to make sure they are correct.
I'm looking for an Objective-C way of sorting characters in a string, as per the answer to this question.
Ideally a function that takes an NSString and returns the sorted equivalent.
Additionally I'd like to run length encode sequences of 3 or more repeats. So, for example "mississippi" first becomes "iiiimppssss", and then could be shortened by encoding as "4impp4s".
I'm not expert in Objective-C (more Java and C++ background) so I'd also like some clue as to what is the best practice for dealing with the memory management (retain counts etc - no GC on the iphone) for the return value of such a function. My source string is in an iPhone search bar control and so is an NSString *.
int char_compare(const char* a, const char* b) {
if(*a < *b) {
return -1;
} else if(*a > *b) {
return 1;
} else {
return 0;
}
}
NSString *sort_str(NSString *unsorted) {
int len = [unsorted length] + 1;
char *cstr = malloc(len);
[unsorted getCString:cstr maxLength:len encoding:NSISOLatin1StringEncoding];
qsort(cstr, len - 1, sizeof(char), char_compare);
NSString *sorted = [NSString stringWithCString:cstr encoding:NSISOLatin1StringEncoding];
free(cstr);
return sorted;
}
The return value is autoreleased so if you want to hold on to it in the caller you'll need to retain it. Not Unicode safe.
With a bounded code-set, radix sort is best:
NSString * sortString(NSString* word) {
int rads[128];
const char *cstr = [word UTF8String];
char *buff = calloc([word length]+1, sizeof(char));
int p = 0;
for(int c = 'a'; c <= 'z'; c++) {
rads[c] = 0;
}
for(int k = 0; k < [word length]; k++) {
int c = cstr[k];
rads[c]++;
}
for(int c = 'a'; c <= 'z'; c++) {
int n = rads[c];
while (n > 0) {
buff[p++] = c;
n--;
}
}
buff[p++] = 0;
return [NSString stringWithUTF8String: buff];
}
Note that the example above only works for lowercase letters (copied from a specific app which needs to sort lowercase strings). To expand it to handle all of the ASCII 127, just do for(c=0; c <= 127; c++).