如何将NSString插入NSMutableString?

时间:2012-04-13 10:29:21

标签: iphone objective-c ios5 nsstring nsmutablestring

我有一个NSMutableString,我需要在两个地方插入另一个NSString。我的NSMutableString是

NSMutableString *webServiceLinkWithResponses = [[NSMutableString alloc] initWithString:@"http://lmsstaging.2xprime.com/services/ParticipantService.cfc?method=setVideoExamResults&student_id=10082&course_id=VRT_TRA&lesson=904&examtype=r&question_num=&ansValue="];

我需要在“question_num =”之后插入一个String(一个),在“ansValue =”之后插入另一个字符串(One),所以我的最后一个字符串应该像

http://lmsstaging.com/services/ParticipantService.cfc?method=setVideoExamResults&student_id=10082&course_id=VRT_TRA&lesson=904&examtype=r&question_num=One&ansValue=One

对此有何建议?

3 个答案:

答案 0 :(得分:5)

以下内容将创建一个未经取消的NSMutableString

NSMutableString *webServiceLinkWithResponses = [NSMutableString stringWithFormat:@"http://lmsstaging.2xprime.com/services/ParticipantService.cfc?method=setVideoExamResults&student_id=10082&course_id=VRT_TRA&lesson=904&examtype=r&question_num=%@&ansValue=%@", stringOne, stringTwo];

如果您需要保留它,只需使用[[NSMutableString alloc] initWithFormat:@"..."]

NSMutableString *webServiceLinkWithResponses = [[NSMutableString alloc] initWithFormat:@"http://lmsstaging.2xprime.com/services/ParticipantService.cfc?method=setVideoExamResults&student_id=10082&course_id=VRT_TRA&lesson=904&examtype=r&question_num=%@&ansValue=%@", stringOne, stringTwo];

你真的需要它成为一个可变的字符串,你是否会在创建后更改它?如果不是简单地将NSMutableString更改为NSString,例如(这会返回自动释放的NSString,如果您需要保留,则使用[NSString alloc] initWithFormat:]

NSString *webServiceLinkWithResponses = [NSString stringWithFormat:@"http://lmsstaging.2xprime.com/services/ParticipantService.cfc?method=setVideoExamResults&student_id=10082&course_id=VRT_TRA&lesson=904&examtype=r&question_num=%@&ansValue=%@", stringOne, stringTwo];

答案 1 :(得分:4)

试试这个:

NSMutableString *webServiceLinkWithResponses = [[NSMutableString alloc] initWithString:[NSString stringWithFormat: @"http://lmsstaging.2xprime.com/services/ParticipantService.cfc?method=setVideoExamResults&student_id=10082&course_id=VRT_TRA&lesson=904&examtype=r&question_num=%@&ansValue=%@",yourFirstString,yourSecondString];

告诉我它是否有帮助!

答案 2 :(得分:2)

我的方式是:

NSMutableString *webServiceLinkWithResponses = [[[NSString stringWithFormat: @"http://lmsstaging.2xprime.com/services/ParticipantService.cfc?method=setVideoExamResults&student_id=10082&course_id=VRT_TRA&lesson=904&examtype=r&question_num=%@&ansValue=%@",yourFirstString,yourSecondString] mutableCopy] autorelease];

根据dreamlax的提示,你也可以使用:

NSMutableString *webServiceLinkWithResponses = [NSMutableString stringWithFormat:@"http://lmsstaging.2xprime.com/services/ParticipantService.cfc?method=setVideoExamResults&student_id=10082&course_id=VRT_TRA&lesson=904&examtype=r&question_num=%@&ansValue=%@", stringOne, stringTwo];