Frage

Possible Duplicate:
C++ String Length?

I really need a help now. How to accept string as input and find the length of the string? I just want a simple code just to know how it works. Thanks.

War es hilfreich?

Lösung

You can use strlen(mystring) from <string.h>. It returns the length of a string.

Remember: A string in C is an array of chars which ends in character '\0'. Providing enough memory is reserved (the whole string + 1 byte fits on the array), the length of the string will be the number of bytes from the pointer (mystring[0]) to the character before '\0'

#include <string.h> //for strlen(mystring)
#include <stdio.h> //for gets(mystring)

char mystring[6];

mystring[0] = 'h';
mystring[1] = 'e';
mystring[2] = 'l';
mystring[3] = 'l';
mystring[4] = 'o';
mystring[5] = '\0';

strlen(mystring); //returns 5, current string pointed by mystring: "hello"

mystring[2] = '\0';

strlen(mystring); //returns 2, current string pointed by mystring: "he"

gets(mystring); //gets string from stdin: http://www.cplusplus.com/reference/clibrary/cstdio/gets/

http://www.cplusplus.com/reference/clibrary/cstring/strlen/

EDIT: As noted in the comments, in C++ it's preferable to refer to string.h as cstring, therefore coding #include <cstring> instead of #include <string.h>.

On the other hand, in C++ you can also use C++ specific string library which provides a string class which allows you to work with strings as objects:

http://www.cplusplus.com/reference/string/string/

You have a pretty good example of string input here: http://www.cplusplus.com/reference/string/operator%3E%3E/

In this case you can declare a string and get its length the following way:

#include <iostream>
#include <string>

string mystring ("hello"); //declares a string object, passing its initial value "hello" to its constructor
cout << mystring.length(); //outputs 5, the length of the string mystring
cin >> mystring; //reads a string from standard input. See http://www.cplusplus.com/reference/string/operator%3E%3E/
cout << mystring.length(); //outputs the new length of the string

Andere Tipps

Hint:

std::string str;
std::cin >> str;
std::cout << str.length();

in c++:

#include <iostream>
#include <string>

std::string s;
std::cin >> s;
int len = s.length();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top