12.1.字符串连接

问题
我想把零散的多个字符串连接成一个
解决办法
使用连接操作符+,或者简写成+=,或者使用String.concat( )方法
讨论
使用+操作符可把多个字符串连接成一个字符串:
+展开
-ActionScript
// 连接成的字符串为"Thisworks" (中间没有空格)
var example:String = "This" + "works";

可一次连接多个字符串:
+展开
-ActionScript
// 结果为"This works" (中间有空格)
var example:String = "This" + " " + "works";

还可以连接其他类型的数据(自动转换为字符串),例如:
+展开
-ActionScript
var attendance:int = 24;
// 结果为"There are 24 people"
var output:String = "There are " + attendance + " people";

+操作符会在连接之前把其他类型的数据转换为字符串后再进行连接,上面的例子把整型的24转换为字符串进行了连接,但是如果所有的待连接的数据都是数字,那编译器就会报错:
+展开
-ActionScript
var first:int = 24;
var second:int = 42;
// 结果编译器报错"Implicit coercion of a value
// type 'Number' to an unrelated type 'String'"
var result:String = first + second;

这时有个技巧就是在前面加个空字符串:
+展开
-ActionScript
var first:int = 24;
var second:int = 42;
// 结果为"2442"
var result:String = "" + first + second;

而且空字符串必须放在表达式的最前面,这样后面的都将被转换为字符串:
+展开
-ActionScript
var first:int = 24;
var second:int = 42;
// 结果为"66"
var result:String = first + second + "";

另一个方法就是使用String( )转换函数(强制类型转换):
+展开
-ActionScript
var first:int = 24;
var second:int = 42;
//结果为"2442"
var result:String = String( first ) + second;

而且要转换的必须是表达式的最前面的那个变量,下面的例子结果是不正确的:
+展开
-ActionScript
var first:int = 24;
var second:int = 42;
var third:int = 21;
// 结果为"6621"
var result:String = first + second + String( third );

另一个方法就是直接使用对象的toString( )方法,Number和int数据类型都有toString( )方法:
+展开
-ActionScript
var first:int = 24;
var second:int = 42;
var third:int = 21;
//结果为"244221"
var result:String = first.toString() + second + third;

如果想在连接的表达式中进行加法运算,加法表达式必须放在括号中:
+展开
-ActionScript
var first:int = 24;
var second:int = 42;
//结果为"There are 66 people"
var result:String = "There are " + ( first + second ) + " people";

通过+= 操作符可追加字符串:
+展开
-ActionScript
var attendance:int = 24;
var example:String = "There are ";
example += attendance;
// 结果为"There are 24 people"
example += " people";

这种技术很友好好处,比如你的字符串过长,即可用这种方法把字符串分成多个字串,然后逐个追加上去,从代码上看更容易阅读:
+展开
-ActionScript
var example:String = "This is the first sentence in a long paragraph of text.";
example += "By adding line by line to the string variable you make ";
example += "your code more readable.";

你也可以这样写:
+展开
-ActionScript
var example:String = "This is the first sentence in a long paragraph of text. "
"By splitting the long string into smaller, more manageable pieces "
"and using the + operator, you can make your code more readable.";

字符串连接最常见的可能就是聊天程序了,比如聊天程序的历史纪录,聊天内容通过字符串连接会不断地追加历史纪录中,例如:
+展开
-ActionScript
// 下面的方法追加姓名和消息到聊天历史纪录中
private function updateChatHistory( message:String, username:String ):void {
// 历史纪录:history 变量
_history += username + ":" + message + '\n';
};

通过String.concat( )方法也可以把新字符串追加到指定的字符串中,该方法不会影响源字符串,而是返回一个新的字符串作为连接结果:
+展开
-ActionScript
var original:String = "original string value.";
// 设置modified变量保存连接结果"original string value.now modified."
// 源original保持不变
var modified:String = original.concat( "now modified." );

加支付宝好友偷能量挖...


评论(0)网络
阅读(92)喜欢(0)flash/flex/fcs/AIR