C++ String Length

String Length

To get the length of a string, use the length() function:

Example:

#include <iostream>
#include <string>
using namespace std;

int main() {
  string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  cout << "The length of the txt string is: " << txt.length();
  return 0;
}


// Output---> The length of the txt string is: 26 

Tip: You might see some C++ programs that use the size() function to get the length of a string. This is just an alias of length(). It is completely up to you if you want to use length() or size():

#include <iostream>
#include <string>
using namespace std;

int main() {
  string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  cout << "The length of the txt string is: " << txt.size();
  return 0;
}


// Output---> The length of the txt string is: 26 

Access Strings

You can access the characters in a string by referring to its index number inside square brackets [].

This example prints the first character in myString:

#include <iostream>
#include <string>
using namespace std;

int main() {
  string myString = "Hello";
  cout << myString[0];
  return 0;
}

// Output---> H

Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.

This example prints the second character in myString:

#include <iostream>
#include <string>
using namespace std;

int main() {
  string myString = "Hello";
  cout << myString[1];
  return 0;
}

//Output---> e

Change String Characters

To change the value of a specific character in a string, refer to the index number, and use single quotes:

#include <iostream>
#include <string>
using namespace std;

int main() {
  string myString = "Hello";
  myString[0] = 'J';
  cout << myString;
  return 0;
}

//Output---> Jello

Leave a Reply

Your email address will not be published.