From: Daniel on
Using c/c++, how do I read the last char in a string and remove the last
character from that string?

Daniel


From: Norman Bullen on
Daniel wrote:

> Using c/c++, how do I read the last char in a string and remove the last
> character from that string?
>
> Daniel
>
>
Echoing comments from the other thread which you started: you need to be
more specific about the language that you're using. Strings are
different in C and C++.

In C you find the length of a string with strlen(). Since a string is
simple an array of characters (str[], for example), the NUL character
that terminates the string follows that length of characters; it is at
str[strlen(str)]. The last non-NUL character is a str[strlen(str)-1].
And you can remove the last character from a string by setting
str[strlen(str)-1] to NUL.

--
Norm

To reply, change domain to an adult feline.

From: Giovanni Dicanio on

"Daniel" <Mahonri(a)cableone.net> ha scritto nel messaggio
news:uTaMLjpyIHA.3628(a)TK2MSFTNGP05.phx.gbl...
> Using c/c++, how do I read the last char in a string and remove the last
> character from that string?

TCHAR * str;

// Get last character (assuming non-empty string!)
TCHAR lastChar = str[ _tcslen( str ) - 1 ];

// Remove last character : replace it with \0
str[ _tcslen( str ) - 1 ] = _T('\0' );

This works for both ANSI/MBCS and Unicode strings.


HTH,
Giovanni



From: Daniel on
I was able to do as you prescribed. Now how do I concatenate the single
char value defined as char to the end of a string defined as char str[10]?

Daniel

"Norman Bullen" <norm(a)BlackKittenAssociates.com> wrote in message
news:5sWdnXFOdMX8QdDVnZ2dnUVZ_jCdnZ2d(a)earthlink.com...
> Daniel wrote:
>
>> Using c/c++, how do I read the last char in a string and remove the last
>> character from that string?
>>
>> Daniel
> Echoing comments from the other thread which you started: you need to be
> more specific about the language that you're using. Strings are different
> in C and C++.
>
> In C you find the length of a string with strlen(). Since a string is
> simple an array of characters (str[], for example), the NUL character that
> terminates the string follows that length of characters; it is at
> str[strlen(str)]. The last non-NUL character is a str[strlen(str)-1]. And
> you can remove the last character from a string by setting
> str[strlen(str)-1] to NUL.
>
> --
> Norm
>
> To reply, change domain to an adult feline.
>


From: David Wilkinson on
Daniel wrote:
> I was able to do as you prescribed. Now how do I concatenate the single
> char value defined as char to the end of a string defined as char str[10]?

aniel:

What is already in this char[10]? Maybe there is no room for another character,
and to try to add one could cause a buffer overrun.

Much better to use std::string (or CString):

char c = '!';
std::string str = "Hello World";
str += c;
assert(str == "Hello World!");

--
David Wilkinson
Visual C++ MVP