Tutorial:BeanShell/4 Strings

From HandWiki


Here we take a look at the various methods of manipulating strings, covering things from basic methods to regular expressions.

String Methods

The most basic way to manipulate strings is through the methods that are build into them. We can perform a limited number of tasks to strings through these methods. Let's create a string:

<jc lang="bsh"> test ="My first string"; print(test); </jc>

Let us count the number of characters in this string, i.e. we want to calculate its length. Use the function length():

<jc lang="bsh"> test = "My first string"; print( test.length() ); </jc>

Let's take our string and replace a word using the replace method:

<jc lang="bsh"> test = "My first string"; test = test.replace ( "first", "second" ); print(test); </jc>

To find a character or words, use "find". It finds the first occurrence of a given character or a word:

<jc bsh edit> t="My first string"; index=t.indexOf("s"); print(index); First occurrence index=t.lastIndexOf("ri"); print(index); Last occurrence index=t.lastIndexOf("OK"); print(index); Not found </jc>

<jnote> Exercise: Replace the character "s" in the above example by "ng" and print the answer. Try other combinations as well