How to get the number of characters in a std::string?
If you're using a std::string
, call length()
:
std::string str = "hello";
std::cout << str << ":" << str.length();
// Outputs "hello:5"
If you're using a c-string, call strlen()
.
const char *str = "hello";
std::cout << str << ":" << strlen(str);
// Outputs "hello:5"
Or, if you happen to like using Pascal-style strings (or f***** strings as Joel Spolsky likes to call them when they have a trailing NULL), just dereference the first character.
const char *str = "\005hello";
std::cout << str + 1 << ":" << *str;
// Outputs "hello:5"
How to calculate number of different number of characters in a string data in c++?
The best way to do is a method called frequency checking. Basically create a vector of size 128. Go through the string and for every character, increment the frequency that matches its ASCII value. Finally, iterate over the freq vector and count how many non zero entries you have. Code should look like this:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
string s = "Hello World";
vector<int>freq(128);
for(int i = 0; i < s.length(); i++)
freq[s[i]]++;
int counter = 0;
for(int i = 0; i < 128; i++)
if(freq[i] > 0)
counter++;
cout << counter << "\n";
}
Vector of size 128 works fine because ASCII codes only go from 0 to 127.
Another way is to initialize a std::set
and insert every character of the string into that one at a time. Finally, output the size of the set. This works because set doesn't allow duplicate entries. The code for this looks like:
#include<iostream>
#include<set>
#include<string>
using namespace std;
int main()
{
string s = "Hello World";
set<char>x;
for(int i = 0; i < s.length(); i++)
x.insert(s[i]);
cout << x.size() << "\n";
}
C++ selecting N characters from string
You can use substr()
:
std::string a = "abcde";
std::string b = a.substr(0, 3);
Notice that indexing starts at 0
.
If you want to shorten the string itself, you can indeed use erase()
:
a.erase(3); // removes all characters starting at position 3 (fourth character)
// until the end of the string
Copy specific number of characters from std::basic_istream to std::string
Just read it directly into the result
string.
#include <sstream>
#include <string>
#include <iostream>
#include <exception>
int main()
{
std::stringstream inss{std::string{R"(some/path/to/a/file/is/stored/in/50/chars Other data starts here.)"}};
std::string result(50, '\0');
if (!inss.read(&result[0], result.size()))
throw std::runtime_error("Could not read enough characters.\n");
std::cout << "Path is: " << result << '\n';
std::cout << "stringstream still has: " << inss.str() << '\n';
return 0;
}
Since C++11, the following guarantee about the memory layout of the std::string
(from cppreference).
The elements of a
basic_string
are stored contiguously, that is, for abasic_string s
,&*(s.begin() + n) == &*s.begin() + n
for anyn
in[0, s.size())
, or, equivalently, a pointer tos[0]
can be passed to functions that expect a pointer to the first element of aCharT[]
array.
(since C++11)
How can I get the number of characters from an input string?
You have to use getline()
instead of cin
to get all line up to newline. cin
reads input up to whitespace.
std::getline (std::cin,Name);
If you use using namespace std;
getline (cin,Name);
If you want to count the input string excluding spaces, the code snippet helps you.
#include <algorithm>
#include <string>
int main()
{
std::string s = "Hello there, world!";
std::cout << std::count( s.begin(), s.end(), ' ' ) << std::endl;
}
Selecting only the first few characters in a string C++
Just use std::string::substr
:
std::string str = "123456789abc";
std::string first_eight = str.substr(0, 8);
Get number of characters in string?
You can use mblen
to count the length or use mbstowcs
source:
http://www.cplusplus.com/reference/cstdlib/mblen/
http://www.cl.cam.ac.uk/~mgk25/unicode.html#mod
The number of characters can be counted in C in a portable way using
mbstowcs(NULL,s,0). This works for UTF-8 like for any other supported
encoding, as long as the appropriate locale has been selected. A
hard-wired technique to count the number of characters in a UTF-8
string is to count all bytes except those in the range 0x80 – 0xBF,
because these are just continuation bytes and not characters of their
own. However, the need to count characters arises surprisingly rarely
in applications.
you can save a unicode char in a wide char wchar_t
A way to use the STL to count chars in a vector of std::string?
To start, you do not need the second loop:
for(int i = 0; i < str.size(); ++i) {
chars += str[i].size();
}
Now for the Standard Library solution:
int chars = accumulate(str.begin(), str.end(), 0, [](int sum, const string& elem) {
return sum + elem.size();
});
Here is a demo on ideone.
Related Topics
In Either C or C++, Should I Check Pointer Parameters Against Null/Nullptr
How to Get the CPU Usage Per Thread on Windows (Win32)
Nonfree Module Is Missing in Opencv 3.0
C++ Return Value Created Before or After Auto Var Destruction
Access Array Beyond the Limit in C and C++
C++ Preprocessor: Avoid Code Repetition of Member Variable List
List of Standard Header Files in C and C++
How Does the Custom Deleter of Std::Unique_Ptr Work
Tools to Find Included Headers Which Are Unused
Setupdigetdeviceproperty Usage Example
How to Use Unique_Ptr for Pimpl
Determining If a Number Is Prime
How Would I Load a Png Image Using Win32/Gdi (No Gdi+ If Possible)
Operator< Comparing Multiple Fields
Why Does VS Not Define the Alternative Tokens for Logical Operators
How to Avoid Repeating the Class Name in the Implementation File