Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

change length of string

FargothFargoth Member Posts: 5
Just a quick question:

I have a string e.g.

char *str;

and I need a function that when called will truncate it shorter (gets rid of the end) or increase the length (fills the end with NULL).

Please can someone give me an example of how to do this. Thanks.

Comments

  • rbarreirarbarreira Member Posts: 22
    [b][red]This message was edited by rbarreira at 2002-10-27 11:19:43[/red][/b][hr]
    The answer to your first question is to simply put a 0 (or '') in the string position you wish that it ends at. For example:

    char str[5] = "asdf";
    str[2] = ''; // '' is exactly equal to 0
    printf ("%s
    ", str);

    Will print "as" on the screen, since the 'd' character was replaced by the string terminator 0.

    Your second question is a bit strange, since C doesn't work like that. A strings's length is defined by where the '' is (all characters after that are ignored), what do you mean increasing the string's length?

    : Just a quick question:
    :
    : I have a string e.g.
    :
    : char *str;
    :
    : and I need a function that when called will truncate it shorter (gets rid of the end) or increase the length (fills the end with NULL).
    :
    : Please can someone give me an example of how to do this. Thanks.
    :



  • ManningManning Member Posts: 1,621
    : Just a quick question:
    :
    : I have a string e.g.
    :
    : char *str;
    :
    : and I need a function that when called will truncate it shorter (gets rid of the end) or increase the length (fills the end with NULL).
    :
    : Please can someone give me an example of how to do this. Thanks.
    :

    Sounds like you want to use the realloc() function. It doesnt zero the bytes if you increase the size of the memory block (the string in this case) so you would have to call memset afterwards.
  • Andre YoungAndre Young USAMember Posts: 0

    _ / http://forcoder.org / free ebooks and video tutorials about { Objective-C, Assembly, R, Go, C, Swift, JavaScript, C#, Delphi, PL/SQL, MATLAB, Ruby, Visual Basic .NET, Python, C++, PHP, Java, Scratch, Perl, Visual Basic F#, ABAP, ML, SAS, Awk, Scala, D, Bash, Julia, Ada, Logo, Transact-SQL, Erlang, Lisp, Scheme, VBScript, COBOL, Apex, Crystal, Dart, Kotlin, Rust, LabVIEW, Hack, Clojure, Prolog, Alice, FoxPro, Fortran, Lua } ___________

Sign In or Register to comment.