• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 231
  • Last Modified:

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 ?
0
apparition
Asked:
apparition
  • 4
  • 2
1 Solution
 
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
 
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
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
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
 
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

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now