C++ Tutorials

C++ Tutorials

C++ programs that use the size() function to get the length of a string. This is just an alias of length(). std::string::length · Parameters none · Return Value The number of bytes in the string. Example 1 · Complexity C++98 · Iterator validity No changes. C++ String class has length() and size() function. These can be used to get the length of a string type object.

We will learn about strings in C++. C++ comes with a library for string which comes with very important and useful functions. Let’s learn about them in this tutorial.

C++ string class internally uses char array to store character but all memory management, allocation and null termination is handled by string class itself that is why it is easy to use.

The length of c++ string can be changed at runtime because of dynamic allocation We will be using the library bits/stdc++.h from here on as it includes all the libraries in C++.

To declare a string variable we write string followed by the variable name. Just like, normal variables. To initialize a string we write the string in double quotes inside parenthesis of the string. Like this. Let’s print this string.

We just need to write cout to print this string. We can see that the output is as expected. To initialize a string with multiple occurance of a character or substring, we write the number of occurrences we want then a comma followed by the substring in quotes.

Here, we are printing a string with 5 stars. Let’s run this code, we can see that the output is as expected. We can find the length of string using .length() function.

To use this, we just need to write variable name dot length() like this. To find the character at some index we use the .at function, here we are finding the value at index 4. To clear a string, we write variable name.clear().

Let’s run this code, we can see that the output is as expected. To append a substring to a string we use .append function. Like, here in this case we are appending forgeeks to s1.

The substr function prints the substring of length b starting from index a. If we do not pass b in the function, it automatically takes this value as length-1. Let’s run this code, we can see that s2 is appended to s1. And the substring Geeks is printed.

To delete specific part of a string we use the erase the function. This function deletes a string of length b starting from the index a. Here, we are deleting a substring of length 3 from index 3. Let’s run this code, we can see that the output is as expected.

To find a pattern or substring in a string we use the find function, this returns the index at which the substring is found, else it returns 0. Like, here we are finding “for” in “GeeksforGeeks”. To replace a substring of a string, we use .replace function. This function replaces b characters from a index with “str”.

Here, we are replacing for with “are”. Let’s run this code, we can see that for is found at the index 5 and it is replaced with are.

Substring C++

How to count number of substrings with exactly k distinct characters. Let’s have a look at the problem statement. Given a string of lowercase alphabets, count all possible substrings (not necessarily distinct) that have exactly k distinct characters.

For example, for input string “abc” and k=2, the output will be 2 as we can have 2 possible substrings with exactly k distinct characters: ab and bc. For input string “aba” and k=2, the output will be 3 as we can have 3 possible substrings with exactly k distinct characters: ab, ba and aba.

For input string “aa” and k=1, the output will be 3 as we can have 3 possible substrings with exactly k distinct characters: the first a, the second a, and aa. Now let’s have a look at the solution.

First method is brute force method. If the length of string is n, then there can be n(n+1)/2 possible substrings. A simple way is to generate all the substring and check each one whether it has exactly k unique characters or not.

If we apply this brute force, it would take O(nn) to generate all substrings and O(n) to do a check on each one. Thus overall it would go O(nnn). The problem can be solved in O(n*n).

Idea is to maintain a hash table while generating substring to store count of each character and checking the number of unique characters using that hash table. Let’s have a look at the implementation.

We assume that the input string contains only characters from small ‘a’ to small ‘z’. We calculate n= str.length() which is the length of our input string. We initialize result as 0.

We create count array cnt to store count of characters from ‘a’ to ‘z’. Hence, the size of the array is 26, for the 26 alphabets. Then to generate substrings, we use 2 loops. In the first loop, i goes from 0 to n and in the inner loop j goes from i to n.

Also, we set dist_count: the count of distinct characters as 0 and initialize count array with 0. Then when we enter the loop we check If str[j] is a new character for the substring, i.e. cnt[str[j] – ‘a’] is 0 then increment dist_count. Also, Increment count of current character as cnt[str[j] – ‘a’]++.

If distinct character count becomes k, then we do result++. Finally we will return the value of result The time complexity of this solution is O(n2) as there are 2 loops in it.

Strlen C++

C++ strlen() is an inbuilt function that is used to calculate the length of the string. It is a beneficial method to find the length of the string. The strlen() function is defined under the string. h header file.

How do I use strlen in C++: The header file <string. h> . In C++, including <string. h> places strlen into the global namespace, while including <cstring> instead places strlen into the std namespace.

Used: strlen() function in C++ returns the length of the given string

Array Length C++

sizeof() operator can be used to find the length of an array. A program that demonstrates the use of the sizeof operator in C++

Finds size of arr[] and stores in ‘size‘ int size = sizeof(arr)/sizeof(arr[0]);.

size() function is used to return the size of the list container or the number of elements in the list container. Syntax : arrayname.size()

Used:

  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. int arr[] = {10,20,30,40,50,60};
  5. int arrSize = sizeof(arr)/sizeof(arr[0]);
  6. cout << “The size of the array is: ” << arrSize;
  7. return 0;

How to find length of string in C++

determine the number of elements in the array, we can divide the total size of the array by the size of the array element. You could do this with the type, like this: int a[17]; size_t n = sizeof(a) / sizeof(int);

  • Using sizeof()
  • sizeof()
  • Using pointer arithmetic
int arrSize = *(&arr + 1) - arr;
#include <iostream>
using namespace std;

int main() {
  int arr[] = {10,20,30,40,50,60};
  int arrSize = *(&arr + 1) - arr;
  cout << "The length of the array is: " << arrSize;
  return 0;
}

C++ string length vs size

Length() returns the number of characters in the string and size() returns a size_t which is also the same but used to make it consistent with other STL containers. For computing length() , the string iterates through all the characters and counts the length.

size_type size() const noexcept;

Returns: A count of the number of char-like objects currently in the string. Complexity: Constant time.

And

size_type length() const noexcept;

// string::length
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  std::cout << "The size of str is " << str.length() << " bytes.\n";
  return 0;
}

string::size C++

std::string::size · Parameters none · Return Value The number of bytes in the string. C++ String size() · Syntax Consider a string object named as ‘str’.

Given your array of strings, you can most certainly use sizeof(array)/sizeof(array[0]) to get its size and the following program works just fine:

int main()
{
    std::string array[] = { "S1", "S2", "S3" };
    std::cout << "A number of elements in array is: "
              << sizeof(array)/sizeof(array[0]) << '\n';
    foo(array);
}

It is not clear what do you mean by saying that size of elements vary. Size of the elements of any array is always known at compiler-time, no exceptions.

There are, however, situations where the above will not work. Consider the following example:

void foo(std::string array[])
{
    std::cout << "A number of elements in array is: "
              << sizeof(array)/sizeof(array[0]) << '\n';
}

The above code is doomed to fail. It might look a bit weird at first, but the reason for this is actually very simple — this is called array decaying. It means that every time you pass an array to a function, its type is automatically decayed to that of a pointer. So the above function is in fact an equivalent of this:

void foo(std::string *array)
{
}

And if in the first example the sizeof operator returns the total size of an array, in the second example it returns the size of a pointer to that array, which is a totally different thing.

There are usually two ways people go about it. The first is to add a special “last” element of the array so that application can traverse the array until it sees the last element and calculate the array’s length. String literals are the perfect example of this — every string literal ends with ‘\0’ and you can always calculate its length. Here is an example:

static void foo(const std::string *array)
{
    size_t i = 0;
    while (!array[i].empty())
        ++i;
    std::cout << "Array length is: " << i << std::endl;
}

The downside is obviously a need to traverse the array to determine its length. The second way it to always carry array length around, for example:

static void foo(const std::string *array, size_t length)
{
    // ...
}

void bar()
{
    std::string array[] = { "S1", "S2", "S3" };
    foo(array, sizeof(array)/sizeof(array[0]));
}

In C++, you can use a template to deduct array’s length, for example:

template <size_t array_length>
static void foo(const std::string (&array)[array_length])
{
    std::cout << "A number of elements in template array is: "
              << array_length << '\n';
}

Get $100 to try DigitalOcean - Try for Free for 60 Days

X