BeanShellTutorial:4 Strings

From jWork.ORG
Jump to: navigation, search
Limitted access. Reguest membership or login to this link first if you are already a member
Contents

String processing

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:


test ="My first string";
print(test);

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


test = "My first string";
print( test.length() );

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


test = "My first string";
test = test.replace ( "first", "second" );
print(test);

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


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