# Finding a character in a std::basic_stringTCHAR

This topic is 4162 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi all, I have a problem with unicode strings. I have a unicode string containing a filename (for example test.txt). Now, i want to extract the file extension from the string. I use the following function: std::basic_string<TCHAR> FileSystemManager::GetFileExtension( const std::basic_string<TCHAR>& s ) { std::basic_string<TCHAR> extension; size_t i = s.find( L'.', s.length() ); if( i != std::basic_string<TCHAR>::npos ) { extension = s.substr( i+1, s.length() - i ); OutputDebugString( extension.c_str() ); return extension; } else { return L""; } } However, it does not work at all. The function always returns the L"". What am I doing wrong here??? Best Regards, Lonly Coder

##### Share on other sites
I'm not sure why it doesn't work, but there is a logical bug in it. The extension of a file isn't everything after the first '.'. It's everything after the last '.'.

##### Share on other sites
There are a couple of things out of place:
1) you make a call to find with an offset of s.length(), meaning that you'll start looking past the end of the string, naturally finding nothing;
2) as Ezbez said, use find_last_of or something similar;
2) TCHAR is mapped to either a narrow char or a wide char, depending on whether Unicode support is enabled, yet you prepend L to character constants and string literals assuming the latter is always the case (it could be in this case, but it's a bad habit to assume);
4) on these forums, put code between code/source tags.

Here's an update that works for me:
// Foobar.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <windows.h>#include <string>typedef std::basic_string<TCHAR, std::char_traits<TCHAR> > TCharString;TCharString GetFileExtension( const TCharString & s ){	TCharString extension;	TCharString::size_type i = s.find_last_of( _T( '.' ) );	if( i != TCharString::npos )	{		extension = s.substr( i + 1, s.length() - i );		OutputDebugString( extension.c_str() );	}	return extension;}int _tmain(int argc, _TCHAR* argv[]){	GetFileExtension( _T( "test.zip" ) );	return 0;}

##### Share on other sites

Tanks for your help Todo and Ezbez!

Now everything works as it was intended. Originally I intended to use rfind but apparently forgot the "r". However, your solution using find_last_of() is obviously the right way to go.

I'll put code between code/source tags next time I make a post :)

Thanks again!

Best Regards,
Lonly Coder

1. 1
Rutin
47
2. 2
3. 3
4. 4
5. 5

• 13
• 10
• 12
• 10
• 13
• ### Forum Statistics

• Total Topics
632992
• Total Posts
3009755
• ### Who's Online (See full list)

There are no registered users currently online

×