faq48.htm

来自「C++builder学习资料C++builder」· HTM 代码 · 共 59 行

HTM
59
字号


<HTML>

<HEAD>

   <TITLE>Search a TStringList for a specific string</TITLE>

   <META NAME="Author" CONTENT="Harold Howe">

</HEAD>

<BODY BGCOLOR="WHITE">



<CENTER>

<TABLE  BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH="640">



<TR>

<TD>

<H3>

Search a <TT>TStringList</TT> for a specific string

</H3>

<P>

Use the <TT>IndexOf</TT> member function of <TT>TStringList</TT>. <TT>IndexOf</TT>

returns the arrary index of the string's location in the <TT>TStringList</TT>. The

array indices are zero based: the first string is index 0. <TT>IndexOf</TT> returns

-1 if the string was not found in the <TT>TStringList</TT>. Here are some code examples.

</P>

<pre>

<font color="navy">// This code searches TStringList A for a string.</font>

<font color="navy">// Assume TStringList *A configured elsewhere</font>

<b>int</b> nIndex <b>=</b> A<b>-></b>IndexOf<b>(</b><font color="blue">"hello"</font><b>)</b><b>;</b>





<font color="navy">// This code searches TStringList A for a string, and then</font>

<font color="navy">// modifies that item if the string is found.</font>

<font color="navy">// Assume TStringList *A configured elsewhere</font>

<b>int</b> nIndex <b>=</b> A<b>-></b>IndexOf<b>(</b><font color="blue">"hello"</font><b>)</b><b>;</b>

<b>if</b> <b>(</b>nIndex <b>!=</b> <b>-</b><font color="blue">1</font><b>)</b>

    A<b>-></b>Strings<b>[</b>nIndex<b>]</b> <b>=</b> <font color="blue">"GoodBye"</font><b>;</b>





<font color="navy">// This code searches a ListBox for the string "Dr. Dobbs". If</font>

<font color="navy">// the string is not found, it is added to the ListBox</font>

AnsiString str <b>=</b> <font color="blue">"Dr. Dobbs"</font><b>;</b>

<b>if</b><b>(</b>ListBox1<b>-></b>Items<b>-></b>IndexOf<b>(</b>str<b>)</b> <b>==</b> <b>-</b><font color="blue">1</font><b>)</b>

    ListBox1<b>-></b>Items<b>-></b>Add<b>(</b>str<b>)</b><b>;</b>

<b>else</b>

    Application<b>-></b>MessageBox<b>(</b><font color="blue">"Dr Dobbs found in ListBox1"</font><b>,</b><font color="blue">"found"</font><b>,</b>MB_OK<b>)</b><b>;</b>





<font color="navy">// This code modifies a string in the StringList of a ListBox.</font>

<font color="navy">// Assume Edit1 provides the string to search for, and Edit2 contains</font>

<font color="navy">// what that string should be changed to.</font>

<b>int</b> nIndex <b>=</b> ListBox1<b>-></b>Items<b>-></b>IndexOf<b>(</b>Edit1<b>-></b>Text<b>)</b><b>;</b>

<b>if</b><b>(</b>nIndex <b>!=</b> <b>-</b><font color="blue">1</font><b>)</b>

    ListBox1<b>-></b>Items<b>[</b>nIndex<b>]</b> <b>=</b> Edit2<b>-></b>Text<b>;</b>

</pre>



</TD> </TR>



</TABLE>

</CENTER>

</BODY>

</HTML>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?