我想在字符串中放置一个字符串。基本上是伪代码:
"first part of string" + "(varying string)" + "third part of string"
我怎么能在objective-c中这样做?有没有办法在obj-c中轻松连接?谢谢!
答案 0 :(得分:101)
是的,做
NSString *str = [NSString stringWithFormat: @"first part %@ second part", varyingString];
对于连接,您可以使用stringByAppendingString
NSString *str = @"hello ";
str = [str stringByAppendingString:@"world"]; //str is now "hello world"
对于多个字符串
NSString *varyingString1 = @"hello";
NSString *varyingString2 = @"world";
NSString *str = [NSString stringWithFormat: @"%@ %@", varyingString1, varyingString2];
//str is now "hello world"
答案 1 :(得分:12)
主题的变化:
NSString *varying = @"whatever it is";
NSString *final = [NSString stringWithFormat:@"first part %@ third part", varying];
NSString *varying = @"whatever it is";
NSString *final = [[@"first part" stringByAppendingString:varying] stringByAppendingString:@"second part"];
NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendFormat:@"%@ third part", varying];
NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendString:varying];
[final appendString:@"third part"];
答案 2 :(得分:10)
NSString * varyingString = ...;
NSString * cat = [NSString stringWithFormat:@"%s%@%@",
"first part of string",
varyingString,
@"third part of string"];
或只是-[NSString stringByAppendingString:]
答案 3 :(得分:6)
您通常会在此使用-stringWithFormat
。
NSString *myString = [NSString stringWithFormat:@"%@%@%@", @"some text", stringVariable, @"some more text"];
答案 4 :(得分:3)
只做
NSString* newString=[NSString stringWithFormat:@"first part of string (%@) third part of string", @"foo"];
这会给你
@"first part of string (foo) third part of string"
答案 5 :(得分:2)
令我感到惊讶的是,没有一个顶级答案指出在最近的Objective-C版本中(在他们添加文字之后),你可以像这样连接:
<h3 style="position: absolute;left:118px;top: 88px;"
onClick="myFunction()"><button onclick = "myFunction()"> Click Me </button></h3>
<div id="same"></div>
<script>
function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
var text= " ";
var i;
for(i=0; i<5; i++){
text += "The number of times I just burped is " + x +"<br><br>";
}
document.getElementById("same").innerHTML = text ;
}
</script>
</body>
它将导致:
@"first" @"second"
您不能将它与NSString对象一起使用,只能使用文字,但在某些情况下它可能很有用。
答案 6 :(得分:0)
简单的一个:
[[@"first" stringByAppendingString:@"second"] stringByAppendingString:@"third"];
如果要连接多个STRINGS,则应使用NSMutableString
以获得更好的性能