for (int i=0; i<[rawNumber length]; i++) {
NSString* chr = [rawNumber substringWithRange:NSMakeRange(i, 1)];
if(doesStringContain(#"0123456789", chr)) {
telNumber = [telNumber stringByAppendingFormat:#"%#", chr];
}
}
What's the logic of this? What does this argument return?
Looks like it's stripping out all the non-numeric characters, to give you a plain old phone number.
I imagine telNumber is defined before this loop, and uses the value of telNumber somewhere else.
Lets say rawNumber held the following value: (987)-654-3210. The for loop runs 14 times total, since that's the length of rawNumber. Each time through, the code gets a single character - the first time it gets the first character, the second time the second character, etc. Each time through the loop, the code checks if the character is in the string 0123456789; if it is, then the code appends the character to the telNumber variable. If the character is not in the list of numbers (if it's ( or ) or - in our example), then it's just discarded.
Related
I have a any challenge. I must write brainfuck-code.
For a given number n appoint its last digit .
entrance
Input will consist of only one line in which there is only one integer n ( 1 < = n < = 2,000,000,000 ) , followed by a newline ' \ n' (ASCII 10).
exit
On the output has to find exactly one integer denoting the last digit of n .
example I
entrance: 32
exit: 2
example II:
entrance: 231231132
exit: 2
This is what I tried, but it didn't work:
+[>,]<.>++++++++++.
The last input is the newline. So you have to go two memory positions back to get the last digit of the number. And maybe you don't have to return a newline character, so the code is
,[>,]<<.
Nope sorry, real answer is
,[>,]<.
because your answer was getting one too far ;)
Depending on the interpreter, you might have to escape the return key by yourself. considering the return key is ASCII: 10, your code should look like this :
>,----- -----[+++++ +++++>,----- -----]<.
broken down :
> | //first operation (just in case your interpreter does not
support a negative pointer index)
,----- ----- | //first entry if it's a return; you don't even get in the loop
[
+++++ +++++ | //if the value was not ASCII 10; you want the original value back
>, | //every next entry
----- ----- | //check again for the the return,
you exit the loop only if the last entered value is 10
]
<. | //your current pointer is 0; you go back to the last valid entry
and you display it
Your issue is that a loop continues for forever until at the end of the loop the cell the pointer is currently on in equal to 0. Your code never prints in the loop, and never subtracts, so your loop will never end, and all that your code does is take an ASCII character as input, move one forward, take an ASCII character as input, and so on. All of your code after the end of the loop is useless, because that your loop will never end.
I have just started learning Java and I reached till arrays , I was preparing this program(From a book) on replacing space ' ' with '.' (dots) and i am not able to understand this specific line (its not mentioned even in the book I am learning from).
Please help me out.
class SpaceRemover{
public static void main(String[] args){
String mostFamous = "Hey there stackoverFLow ";
char [] mf1 = mostFamous.toCharArray();
for(int dex = 0; dex<mf1.length;dex++)
{
char current = mf1[dex]; // What is happening in this line ??
if (current != ' ') {
System.out.print(current);
}
else{
System.out.print('.');
}
}
System.out.println();
}
}
Someone please explain what is happening in "char current = mf1[dex];"
Thanks a lot for your time.
You are getting the dexth character/item within the character array mf1 (hence mf1[dex]) and storing it into the local variable current.
Basically a String in java is an array of characters. So what the above code does is converts the string to an array of chars so that it can access each index of the array later on. Then the code enters into a for loop in order to iterate through all the indecies of the char array.
Assuming that that is already clear to you, the code now creates a char variable which holds the current index of the array.
char current = mf1[dex];
mf1 is your char array that represents the string. dex is the current index of the char that is determined by the for loop. So by doing this we can check each character (letter) of the char array. Now if the char "current" is a blank space we can replace it with a dot.
It's getting the character at index idx in the array mf1 and storing its value in the current variable.
The for-loop is iterating the string mostFamous character by character.
the line you are asking is to get the character at specific position. Function is similar to JavaScript's charAt(i)
char current = mf1[dex];
This line gets values from the mf1 char array and assign to the current variable according to the dex, dex works as index to the array element and it increments with the running loop.
The line
char current = mf1[dex];
is placed inside a for loop where the variable dex is incremented each time the loop is iterated. The variable dex is the zero-based index of the array. On the left hand side of the assignment operator (=), you are declaring a variable named current of type char. On the right hand side of the assignment operator you are accessing the dex-th character of your CharArray, if you start counting from zero. The assignment operator binds the variable you declared with the value of the character you specified on the right hand side.
For example, the first time the loop is run, dex would start at 0, hence mf1[dex] (or mf1[0]) is just 'H'.
Here is solution
class SpaceRemover{
public static void main(String[] args){
String mostFamous = "Hey there stackoverFLow ";
char [] mf1 = mostFamous.toCharArray();
// mf1 contains={'H', 'e','y',' ','t','h',.........}
for(char current: mf1)
{
//the for-each loop assigns the value of mf1 variable to the current variable
//At first time the 'H' is assigned to the current and so-on
System.out.print(current==' '?'.':current );
}
System.out.println();
}
}
}
It assigns the element of the char array mf1 at the index dex to the char variable current.
Note that the for loop and that line may be simplified by using the foreach syntax; these two code blocks are equivalent:
// Your code
for(int dex = 0; dex<mf1.length;dex++) {
char current = mf1[dex];
// Equivalent code
for (char current : mf1) {
But further, the whole method may be replaced by one line:
public static void main(String[] args){
System.out.println("Hey there stackoverFLow ".replace(" ", "."));
}
char current = mf1[dex];
this will return the char element in char array whose index is dex
This is quite a basic usage of array.
Good luck with your study.
After this statement, char [] mf1 = mostFamous.toCharArray();
mf1[0]=H, mf1[1]=e, mf1[1]=y...
so at this line, char current = mf1[dex];
so, in first iteration, current=H, second iteration current=e...
I want URL encoding to be done. My input string is "ChBdgzQ3qUpNRBEHB+bOXQNjRTQ="
I get an output as "ChBdgzQ3qUpNRBEHB%2BbOXQNjRTQ%3D" which is totally correct except the case which gets encoded.
Ideally, it should have been "ChBdgzQ3qUpNRBEHB%2bbOXQNjRTQ%3d" instead of the output I get.
i.e I should have got %2b and %3d instead of %2B and %3D.
Could this be done?
The code I used is as below :
NSString* inputStr = #"ChBdgzQ3qUpNRBEHB+bOXQNjRTQ=";
NSString* outputStr = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)inputStr,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding));
Another perhaps more elegant but slower way would be to loop over your string, converting each character in the string one by one (so you would get the length of your string, then get a substring from it from location 0 to length-1, with one character each time, then translate just that substring. If the returned string has a length > 1, then CFURLCreateStringByAddingPercentEscapes encoded the character, and you can safely turn the case into lower case.
In all cases you append the returned (and possibly modified) string to a mutable string, and when done you have exactly what you want for any possible string. Even though this would appear to be a real processor hog, the reality is you would probably never notice the extra consumed cycles.
Likewise, a second approach would be to just convert your whole string first, then copy it byte by byte to a mutable string, and if you find a "%", then turn the next two characters into lower case. Just a slightly different way to slice the problem.
You can use a regular expression to perform the post operation:
NSMutableString *finalStr = outputStr.mutableCopy;
NSRegularExpression *re = [[NSRegularExpression alloc] initWithPattern:#"(?<=%)[0-9A-F]{2}" options:0 error:nil];
for (NSTextCheckingResult *match in [re matchesInString:escaped options:0 range:NSMakeRange(0, escaped.length)]) {
[finalStr replaceCharactersInRange:match.range withString:[[escaped substringWithRange:match.range] lowercaseString]];
}
The code uses this regular expression:
(<?=%)[0-9A-F]{2}
It matches two hexadecimal characters, only if preceded by a percent sign. Each match is then iterated and replaced within a mutable string. We don't have to worry about offset changes because the replacement string is always the same length.
I am making a UITextView which is similar to notes.app, where the first line of the textView is used as the title. I need to create a new string which contains only the first line of text. So far I've come up with this:
NSRange startRange = NSMakeRange(0, 1);
NSRange titleRange = [noteTextView.text lineRangeForRange:startRange];
NSString *titleString = [noteTextView.text substringToIndex:titleRange.length];
NSLog(#"The title is: %#", titleString);
The only problem with this is that it relies on the user pressing Return. I've also tried using a loop to find the number of characters in the first line:
CGSize lineSize = [noteTextView.text sizeWithFont:noteTextView.font
constrainedToSize:noteTextView.frame.size
lineBreakMode:UILineBreakModeWordWrap];
int textLength =1;
while ((lineSize.width < noteTextView.frame.size.width) &&
([[noteTextView.text substringToIndex:textLength] length] < [noteTextView.text length]))
{
lineSize = [[noteTextView.text substringToIndex:textLength] sizeWithFont:noteTextView.font
constrainedToSize:noteTextView.frame.size
lineBreakMode:UILineBreakModeWordWrap];
textLength = textLength+1;
}
NSLog(#"Length is %i", textLength);
But I've got this wrong somewhere - it returns the total number of characters, instead of the number on the first line.
Does anyone know an easier/better way of doing this?
There is probably a much better way with CoreText, but I'll throw this out there just because it came to mind off the top of my head.
You could add characters one by one to an NSMutableString *title while
[title sizeWithFont:noteTextView.font].width < noteTextView.frame.size.width
then drop the last one, obviously doing the necessary bounds checking along the way and dropping the last added character if necessary.
But sizeWithFont is sloooooow. So if you're doing this often you might want to consider another definition of 'title' - say, at first word break after 20 chars.
But again, CoreText might yield more possibilities.
I do not understand the code you're having above. Wouldn't it be simpler do just find the first line of text in the string, e.g. until a CR or LF terminates the first line?
And if there is no CR or LF, then you take the entire text as you have only one line then.
Of course, this will give you not what is visible in the first line in case the line is longer and gets wrapped, but I think that using lineRangeForRange doesn't do this, either, or does it?
And if your only concern is that "the user has to press enter" to make it work, then why not simply append a newline char to the text before testing for the first line's length?
See how many characters can fit in one line of your text view and use that number in a substringToIndex: method. Like this:
Type out the same character repeatedly and count how many fit in one line. Make sure to use a wide letter to ensure reliability. Use a capital g or m or q or w or whatever is widest in the font you're using.
Say 20 characters can fit in one line.
Then do
NSString *textViewString = notesTextView.text;
NSString *titleString = [textViewString substringToIndex:20]
Just use the titleString as the title.
I am used to doing this in C or C++, ie:
myChar++;
should increment a letter.
I am trying to do the same in Objective-C, except that I have a NSString to start off with (the NSString is always just one letter). I have tried converting the NSString to a char *, but this method is deprecated and other ways of achieving this don't seem to work.
How should I convert an NSString to a char * - or, is there a way to increment a character in objective-c without needing a char * somehow?
Thanks :)
// Get the first character as a UTF-16 (2-byte) character:
unichar c = [string characterAtIndex:0];
// Increment as usual:
c++;
// And to turn it into a 1-character string again:
[NSString stringWithCharacters:&c length:1];
Of course, this assumes incrementing a Unicode character makes sense, which does for ASCII-range characters but probably not for others.
How about NSString's
- (unichar)characterAtIndex:(NSUInteger)index;
Would that work?