techno
techno

Reputation: 6500

Separate String from Integer(Separate Fontname from Font Size)

I have this fontname property which returns fontname+SPACE+fontsize eg: Sans 12 but for creating a font object i need the font name and font size separately.I hope fonts does not have a number in their names.

So im looking for a way to split this string to 2 parts.

Upvotes: 0

Views: 66

Answers (2)

bit
bit

Reputation: 4487

This should give you what you need:

var yourString = "SAN 1 12";
var lastSpace = yourString.LastIndexOf( ' ' );
var fontName = yourString.Substring( 0, lastSpace ); //gives SAN 1
var fontSize = yourString.Substring( lastSpace ).Trim(); //gives 12

Upvotes: 3

Mikayil Abdullayev
Mikayil Abdullayev

Reputation: 12367

Assuming the property returns something like "Some Font2 With 5 Variants 24", you can do the following:

   //fontProperty="Some Font2 With 5 Variants 24"

   string fontNamePart=fontProperty.Substring(0,fontProperty.LastIndexOf(' '));
   int fontSize=int.Parse(fontProperty.Substring(fontProperty.LastIndexOf(' ')+1));

To make the size part "white-space-character-proof" so that it can safely be converted to an int you can additionally trim it before converting. Like this:

   int fontSize=int.Parse(fontProperty.Substring(fontProperty.LastIndexOf(' ')+1).Trim());// I know, looks a bit ugly

This should work on any kind of font provided the last part is always the size of the font.

Upvotes: 1

Related Questions