String Manupulation.

In a string whenever the charcters "DC#" appears, I want to extract the next 4 characters.
So for example, if the string was "LAWRENCE DC#1234 MORE TEXT" I want to extract "1234".
How can this be done ?
LVL 5
apparitionAsked:
Who is Participating?
 
cjjcliffordCommented:
ok, so split on the "DC#", and check the result before doing the substring.

String[] bits = mystring.split( "DC#" );
if( bits.length == 2 ) {
    subs = bits[1].substring( 0, 3 );
}

you can also do this in a regular expression...
0
 
cjjcliffordCommented:
split the string on the '#' and take the first 4 characters of the second section of the split...

mystring.split( "#" ).substring( 0, 4 )
0
 
apparitionAuthor Commented:
I need to make sure the "#" is preceded by "DC"
so if my string was  "BLA # BLA DC#1234 BLA" your solution won't work.
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
cjjcliffordCommented:
sorry, of course split() returns array, and also, substring() takes the second argument as the index to stop the substring, so 3 will be the fourth character...

so...

mystring.split( "#" )[1].substring( 0, 3 )
0
 
apparitionAuthor Commented:
again won't work for a string like  "BLA # BLA DC#1234 BLA"
0
 
cjjcliffordCommented:
thanks - out of interest, the regex impl is along the following lines:

import java.util.regex.*;
...
Matcher matcher = Pattern( ".*DC#(....).*" ).matcher( mystring );
if( matcher.matches() ) {
    substring = matcher.group(1);
}

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.