Printing string character change in C++


This code declares a string variable word and initializes it with the value "Ram". It then modifies the first character of the string to 'S' using the subscript operator, and prints the modified string to the console using cout.

Note that in C++, strings are objects, and you can access and modify individual characters in the string using the subscript operator []. However, modifying a character in a string literal (like "Ram") is not allowed and can result in undefined behavior. It's safer to declare the string as a non-constant variable before modifying it.

Also note that the string.h library is not necessary for this code and can be removed. The string class is included in the standard C++ library and can be used directly.

Source Code

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    string word="Ram";
    word[0]='S';
    cout<<"\n"<<word;
    return 0;
}
To download raw file Click Here

Output

Sam


Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples