c++ get first character of string code example

Example 1: index string c++

#include <string>
#include <iostream>

int main(){
  //index string by using brackets []
  std::string string = "Hello, World!";
  //assign variable to string index
  char stringindex = string[2];
  
}

Example 2: get first and last character of string c++

auto first_char = str.front()
auto last_char = str.back()

Example 3: c++ check first character of string

#include <iostream>
#include <string>

int main() 
{
  string str{};     // creating string
  getline(cin, str);// using getline for user input
  std::cout << str; // output string namePerson
  if (str[0] >= 'a' || str[0] <= 'z')
    str[0] -= 32;
  return (0);
}

Example 4: c++ first letter of string

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

int main ()
{
  std::string str ("Test string");
  for (unsigned i=0; i<str.length(); ++i)
  {
    std::cout << str.at(i);
  }
  return 0;
}

Tags:

Java Example