Flex中利用StringUtil类的substitute()方法对字符串中的字符进行替换的例子

By Minidxer | August 24, 2008

很多系统中当用户注册或者作了某项操作的时候,系统会自动发送邮件或者消息给该用户,其中大部分的内容是一样的,不过比如用户名,用户的操作之类的则是不一样的。接下来的例子就演示了Flex中如何利用StringUtil类的substitute()方法,对字符串中的字符进行替换。

让我们先来看一下Demo可以右键View Source或点击这里察看源代码):


下面是完整代码(或点击这里察看):

Download: main.mxml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
  3.         layout="vertical"
  4.         verticalAlign="middle"
  5.         backgroundColor="white">
  6.  
  7.     <mx:Script>
  8.         <![CDATA[
  9.             import mx.utils.StringUtil;
  10.  
  11.             private function button_click(evt:MouseEvent):void {
  12.                 textArea.text = StringUtil.substitute(template,
  13.                                     var0.text,
  14.                                     var1.text,
  15.                                     var2.text,
  16.                                     var3.text,
  17.                                     var4.text,
  18.                                     var5.text);
  19.             }
  20.         ]]>
  21.     </mx:Script>
  22.  
  23.     <mx:String id="template" source="template.txt" />
  24.  
  25.     <mx:HBox width="100%">
  26.         <mx:Form>
  27.             <mx:FormItem label="0:">
  28.                 <mx:TextInput id="var0" text="John Doe" />
  29.             </mx:FormItem>
  30.             <mx:FormItem label="1:">
  31.                 <mx:TextInput id="var1" text="death" />
  32.             </mx:FormItem>
  33.             <mx:FormItem label="2:">
  34.                 <mx:TextInput id="var2" text="Mega Insurance Inc." />
  35.             </mx:FormItem>
  36.             <mx:FormItem label="3:">
  37.                 <mx:TextInput id="var3" text="policy" />
  38.             </mx:FormItem>
  39.             <mx:FormItem label="4:">
  40.                 <mx:TextInput id="var4" text="terminated" />
  41.             </mx:FormItem>
  42.             <mx:FormItem label="5:">
  43.                 <mx:TextInput id="var5" text="serve you" />
  44.             </mx:FormItem>
  45.             <mx:FormItem direction="horizontal">
  46.                 <mx:Button id="button"
  47.                         label="Substitute"
  48.                         click="button_click(event)" />
  49.                 <mx:Button label="Reset"
  50.                         click="textArea.text = template;" />
  51.             </mx:FormItem>
  52.         </mx:Form>
  53.         <mx:TextArea id="textArea"
  54.                 text="{template}"
  55.                 editable="false"
  56.                 width="100%"
  57.                 height="100%" />
  58.     </mx:HBox>
  59.  
  60. </mx:Application>
代码:Peter deHaan 翻译/整理/编译:中文Flex例子

Topics: Flex | No Comments » | Tags: ,

Search Posts