KEMBAR78
String in DS | PDF | String (Computer Science) | Computer Data
0% found this document useful (0 votes)
5 views9 pages

String in DS

Uploaded by

RK
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

String in DS

Uploaded by

RK
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

What is a String?

String is a type of primitive data structure that stores a sequence of characters. It is


typically used for storing, manipulating, and processing texts such as user input,
messages, labels and so on.

Syntax
C++ string creation −

string string_name = "string in double quotes";

Need for Strings


String is the most easiest and preferable way of interaction between an application and
a user. They are easy to understand and use, as they are based on human-readable
characters. Also, they are used to store a wide range of data, such as text, numbers,
symbols, binary, hexadecimal, etc.

String Representation
Like arrays, strings are also represented as a collection of buckets where each bucket
stores one character. These buckets have index from '0' to 'n-1', where n is the length of
that particular string. For instance, a string with size 10 will have buckets indexed from 0
to 9. The figure below illustrates how a string is represented −

Following are some important points from the above representation.

●​ Index always starts with 0.


●​ If the index is from 0 to 9, it means the string has 10 elements.
●​ Each character can be accessed via its index.

Characteristics of Strings

1.​ Immutable: In most programming languages, strings are immutable, meaning


once a string is created, it cannot be changed. Any operation that modifies a
string will create a new string.
2.​ Indexed: Characters in a string are typically accessible via indexing. For
example, in the string “hello”, h is at index 0, e at index 1, and so on.
3.​ Iterable: Strings can be iterated over using loops, allowing for operations on
each character.
4.​ Concatenation: Strings can be concatenated or joined together using
operators or methods.
5.​ Length: The length of a string, or the number of characters it contains, can be
found using specific functions or properties.

Basic Operations on a String


There are many operations that can be performed on strings, such as searching,
splitting, trimming, indexing and so on. Each programming language has its own set of
built-in functions or methods that help in performing these operations with ease.

Following are the basic operations that can be performed on a given string −

​ Concatenation − Joining two or more strings together.


​ Length − Printing the number of characters in a string.
​ Substring − Finding a portion of a bigger string.
​ Reversing − Printing the string characters in reverse order.
​ Indexing − Accessing a particular character using its index.

Concatenation Operation
The concatenation operation is a process of joining two or more strings together to form
a new string.

Algorithm
Following is the algorithm to concatenate two strings.

1. Start
2. Declare and Initialize two strings.
3. Perform concatenation.
4. Print the result.
5. Stop

Example
#include <iostream>
#include <string>
using namespace std;
int main() {
// defining two strings
string sOne = "Data";
string sTwo = "Structure";
// concatenating the strings
string newStr = sOne + sTwo;
// printing the result
cout <<"New String: " << newStr << endl;
}
Output
New String: DataStructure

Finding the Length of a String


Finding length of the string means printing the number of characters in that string. The
length of a string can be used to iterate over its characters, access a specific character
at a given index, or slice a substring from the original string.

Algorithm
The algorithm to find the length of a string is as follows −

1. Start
2. Declare and Initialize a string.
3. Find the number of characters.
4. Print the result.
5. Stop

Example
#include <iostream>
#include <string>
using namespace std;
int main() {
// the string given as
string name = "DataStructure";
// to ind the length of given string
int strLength = name.length();
// to print the result
cout << "The length of given string is: " << strLength << endl;
return 0;
}

Output
The length of given string is: 13

Finding a Substring in a String


A substring refers to a part or subset of a string. In this operation, we need to find the
index of the given substring.

Algorithm
Suppose we have a substring named newSubStr and we need to find its index number.
Following is the algorithm to find substring.

1. Start
2. Declare and Initialize a string.
3. Define a sub-string.
4. Check index of sub-string.
5. If found, print index of first character of sub-string otherwise print "-1".
6. Stop

Example
#include <iostream>
#include <string>
using namespace std;
int main() {
// Original string
string orgnlStr = "DataStructure";
// Substring to find
string newSubStr = "Struct";
// to find index of the substring
int indX = orgnlStr.find(newSubStr);
// Check if the substring is present
if (indX == -1) {
cout << "-1" << endl;
} else {
cout << "Substring found at index: " << indX << endl;
}
return 0;
}

Output
Substring found at index: 4

Reversing the contents of a String


In the Reversing operation, we reverse the order of characters in a string. This will result
in a new string that contains the same characters as the original string, but in the
opposite order.

Algorithm
Suppose we have a string and we need to reverse it. Following is the algorithm to reverse
a string.

1. Start
2. Declare an empty string.
3. Define a for loop to iterate over the characters of original string.
4. Append each character to the reversed string.
5. Print the result.
6. Stop
Example
#include <iostream>
#include <string>
using namespace std;
// function to reverse the string
string rev_str(string orgnlStr) {
// Initializing an empty string
string revStr = "";
// loop to reverse the string
for (int i = orgnlStr.length() - 1; i >= 0; i--) {
// Append each character to the reversed string
revStr += orgnlStr[i];
}
// Return the reversed string
return revStr;
}
int main() {
cout << "Printing the string in reverse order: " << endl;
// calling the function to print the result
cout << rev_str("Data") << endl;
cout << rev_str("Structure") << endl;
return 0;
}

Output
Printing the string in reverse order:
ataD
erutcurtS

Indexing in Strings
In this operation, we try to access or locate a particular character with the help of index.

Algorithm
The algorithm to access a specified character from a given String is as follows −

1. Start
2. Declare and Initialize a string.
3. Find the index number of specified character.
4. Print the result.
5. Stop

Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Data Structure";
int indX = str.find('r');
// print the result
cout << "The index of given character is: " << indX << endl;
return 0;
}

Output
The index of given character is: 7

C++ Strings
C++ provides following two types of string representations −

​ The C-style character string.


​ The string class type introduced with Standard C++.

The C-Style Character String


The C-style character string originated within the C language and continues to be
supported within C++. This string is actually a one-dimensional array of characters
which is terminated by a null character '\0'. Thus a null-terminated string contains the
characters that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word "Hello".
To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization, then you can write the above statement as
follows −

char greeting[] = "Hello";

Following is the memory presentation of above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant. The C++
compiler automatically places the '\0' at the end of the string when it initializes the array.
Example
#include <iostream>

using namespace std;

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: ";


cout << greeting << endl;

return 0;
}

Output

Greeting message: Hello

C Style String Functions


C++ supports a wide range of functions that manipulate null-terminated strings. These
functions are defined in <string.h> header file.

Sr.No Function & Purpose

1 strcpy(s1, s2);
Copies string s2 into string s1.

2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3 strlen(s1);
Returns the length of string s1.

4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.

5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.

Example
Following example makes use of few of the above-mentioned functions −

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

int main () {

char str1[10] = "Hello";


char str2[10] = "World";
char str3[10];
int len ;

// copy str1 into str3


strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation


len = strlen(str1);
cout << "strlen(str1) : " << len << endl;

return 0;
}

Output

strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10

String Functions
String is an object of the <string> class, and hence, it has a variety of functions that
users can utilize for a variety of operations. Some of these functions are as follows −

Function Description

length() This function returns the length of the string.

swap() This function is used to swap the values of 2 strings.

size() Used to find the size of string

resize() This function is used to resize the length of the string up to the
given number of characters.

find() Used to find the string which is passed in parameters

push_back() This function is used to push the character at the end of the
string
pop_back() This function is used to pop the last character from the string

clear() This function is used to remove all the elements of the string.

find() This function is used to search for a certain substring inside a


string and returns the position of the first character of the
substring.

replace() This function is used to replace each element in the range


[first, last) that is equal to old value with new value.

substr() This function is used to create a substring from a given string.

compare() This function is used to compare two strings and returns the
result in the form of an integer.

erase() This function is used to remove a certain part of a string.

You might also like