2009-07-08 3 views
2

나는 guyz에게는 매우 간단 할 수있는 복잡한 질문이 있습니다. Objective C NSMutableString 문/수정 추가 및 적용

은 내가 3 부울을 가지고

NSMutableString = "This is spinach";

있습니다. 코드를 무시하십시오. 나는 적절한 구문, 함수를 사용하지 않았다.

if (boolA) appendstring"and apples"; 

if (boolB) appendstring"and mangoes"; 

if (boolC) appendstring"and oranges"; 

모든 부울은 과일에 해당합니다. BOOL a가 참이라면 나는 또한 망고를 가지고 있다고 말하십시오!

어쨌든, 제 목표는 해당 부울이 참이고 매우 구체적인 방식으로 존재하는 경우 다른 과일을 추가하여 초기 String의 서식을 지정하는 것입니다.

BOOL A가 참이면 "This is spinach and mangoes"문자열이되어야합니다. 망고에 "and"가 추가되었습니다. 끝까지 기다리면 바로 추가 할 수 있습니다.

그러나 문제는 모든 BOOLeans가 참일 때입니다. 문자열은 "이것은 시금치와 사과와 망고와 오렌지입니다."와 같이 나타납니다. 나는 그것이처럼 보이게 할

내가 망고와 오렌지 전에 쉼표를 ","추가 "그리고"한 번만 후 즉시 통지 할 공지 사항 "이것은 시금치와 사과, 망고, 오렌지입니다."

나는 아마도 이것을 얻을 수 있지만 많은 수표와 불필요한 if/else 문의 ALOt가 있습니다.

내가 나타나서 내가이 작업을 수행하는 데 사용할 수있는 기능의 어떤 종류가 추측

"This is spinach and apples and mangoes and oranges" into 
"This is spinach and apples , mangoes , oranges". 

메신저를 켤 수 있다고 생각했다. 두 번째 및 세 번째 ""을 ","으로 바꾸는 것.

여러분은이 기능과 예를 들어 설명해 주시겠습니까? 이것은 CPP에서 다시 가능하다고 생각했습니다. .. strpos()를 사용하여 char의 위치를 ​​얻은 다음 특정 숫자 뒤에 무언가를 수행하고 문자열을 바꿉니다. 아니면 더 나은 방법인지 알려주세요.

답변

0

각 bool을 사용하여 과일 문자열을 배열에 추가합니다.

items = [NSArray new]; 

if (boolA) [items append: @"apples"]; 
if (boolB) [items append: @"bannanas"]; 
if (boolC) [items append: @"cranberries"]; 

그럼 배열의 길이를보고 모든 언어 (영어, 프랑스어 등)에 대해 '올바른'일을합니다.

의사/깨진 Objc 코드 :

r = [NSMutableString string]; 
[r appendString: @"This is "]; 

if ([items length] == 1) { 
    [r appendString: [items at: 0]]; 
} 
if ([items length] == 2) { 
    [r appendStringWithFormat: @"%@ and %@ ", [items at: 0], [items at: 1]] ; 
} 
if ([items length] > 2) { 
    for (int i = 0; i < [items length]; i++) {  
    if (i == ([items length] - 1)) //if last 
     [r appendString: @"and "]; 
    [r appendString: [items at: i]]; 
    [r appendString: @", "]; 
    } 
} 

가 다시 말하지만, 이것은 단지 객관적인 의사 코드입니다. 나는 단지 보다는 당신에게 당신이 당신의 시스템에 붙여 넣어야 할 것을주는 요점을주고 있습니다. 아마도 잘못된 메소드 이름과 mem 누수가 있습니다.

또한 복수형과 단수형을 다루기 시작하면 상황이 훨씬 복잡해 지지만 지나치게 복잡하지는 않습니다.

환호 잘

2

매우 단순하고 순진한 접근 방법은 다음과 같습니다

NSMutableString* message = [NSMutableString stringWithCapacity:15]; 
[message setString:@"This is spinach"]; 

BOOL boolA = YES, boolB = NO, boolC = YES; 

// add "and" if there are any fruits 
if(boolA || boolB || boolC) 
    [message appendString:@" and"]; 

if(boolA) 
    [message appendString:@" apples,"]; 
if(boolB) 
    [message appendString:@" oranges,"]; 
if(boolC) 
    [message appendString:@" mangoes,"]; 

// remove last "," 
if(boolA || boolB || boolC) 
    [message deleteCharactersInRange:NSMakeRange([message length] - 1, 1)]; 

This is spinach and apples, mangoes 
1

여기에 대신 bool1 Bool2를 등

의 배열을 사용하는 청소기 솔루션의 결과

얼마나 많은 bool이 진실인지 확인하십시오. 배열에 배열을 넣고 문자열을 다른 배열에 넣으십시오.) 그러면 출력 할 내용을 알 수 있습니다. 문자열 배열에는 "and"가 아닌 고유 한 과일 만 들어 있어야합니다. 당신은 isand = false라고 불리는 bool을 갖게 될 것입니다; bool 배열을 반복하고, 참이면 다른 배열에 "and"+ 과일 이름을 추가하고 다른 bool을 true로 설정하십시오. 그런 다음 나머지를 위해 더 많은 "and"를 추가하지 말 것입니다.

편집 :

bool isand=false; 
NSMutableArray * strings = [NSMutableArray alloc] init]; 
NSMutableArray * bools = [NSMutableArray alloc] init]; 
NSMutableString = @"This is spinach"; 

//fill arrays with values 

for (NSInt x=0; x<[string length]; x++) //could've used for in, but need to know which index to use in other array 
{ 
if (b) 
{ 
if (!isand) 
{ 
[mystring appendString: @" and "]; 
isand=true; 
} 
[mystring appendString: [strings objectAtIndex: x]; 
} 
} 

아마했습니다 : 즉, 여기에 몇 가지 코드 (D 내 목표 C 구문 내 실수와 의견을 수정하시기 바랍니다, 완벽한, 또는 완벽한 꿈에도 생각하지 않을 수)의 이해하기 어렵다 많은 끔찍한 오류를 만들었지 만 잘하면 당신은 아이디어를 얻을 : D

1

또 다른 해결책, + [NSArray를 componentsJoinedByString :]를 사용하여이 시간

NSMutableArray* fruits = [NSMutableArray arrayWithCapacity:3]; 

if(boolA) 
    [fruits addObject:@"apples"]; 
if(boolB) 
    [fruits addObject:@"oranges"]; 
if(boolC) 
    [fruits addObject:@"mangoes"]; 

NSString* message; 
if([fruits count] > 0) 
    message = [NSString stringWithFormat:@"This is spinach and %@", [fruits componentsJoinedByString:@", "]]; 
else 
    message = @"This is spinach";