一回しか出てこない文字を探すiPhoneアプリのサンプルコード(ObjC++)を描いてみます。
#import “ViewController.h”
#include <memory>
#include <string>
#include <map>
using namespace std;
class UnrepeatChar {
public:
char find(string);
};
char UnrepeatChar::find(string s) {
map<char, int> myMap;
long len = s.length();
for (int i=0; i<len; i++) ++myMap[s[i]];
for (int i=0; i<len; i++)
if (myMap.find(s[i])->second == 1) return s[i];
return 0;
};
@interface ViewController ()
@property (nonatomic, weak) UITextView *textView;
@property (nonatomic) std::shared_ptr<UnrepeatChar> cppClass;
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
UILabel *title = [[UILabel alloc] init];
title.text = @”find unrepeat char”;
[title sizeToFit];
title.center = CGPointMake(CGRectGetMidX(self.view.bounds), 280);
[self.view addSubview:title];
UITextView *tf = [[UITextView alloc] initWithFrame:CGRectMake(30, 50, CGRectGetMaxX(self.view.bounds) – 60, 180)];
tf.font = [UIFont fontWithName:@”Chalkduster” size:20];
tf.backgroundColor = [UIColor brownColor];
tf.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
[self.view addSubview:tf];
self.textView = tf;
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
[btn setTitle:@”Find” forState:UIControlStateNormal];
[btn sizeToFit];
btn.center = CGPointMake(CGRectGetMidX(self.view.bounds), 250);
[btn addTarget:self action:@selector(find) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
– (void)find {
NSString *str = self.textView.text;
std::shared_ptr<UnrepeatChar> cppClass(new UnrepeatChar());
char answer = cppClass->find(*new std::string([str UTF8String]));
NSMutableAttributedString *atts = [[NSMutableAttributedString alloc]initWithString:str];
NSRange range = [str rangeOfString:[NSString stringWithFormat:@”%c”, answer] options:NSForcedOrderingSearch];
[atts addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range];
[atts addAttribute:NSFontAttributeName value:[UIFont fontWithName:@”Chalkduster” size:20] range:NSMakeRange(0, str.length)];
self.textView.attributedText = atts;
}
@end