0% found this document useful (0 votes)
3 views

String Algorithma and code examples

The document provides detailed algorithms and C code for various string operations, including reading characters until a termination character, appending and concatenating strings, converting characters between uppercase and lowercase, comparing strings, and reversing a string. It explains the ASCII representation of characters and the relationship between uppercase and lowercase letters. Each section includes example inputs, outputs, and code snippets to illustrate the concepts.

Uploaded by

nandithamr5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

String Algorithma and code examples

The document provides detailed algorithms and C code for various string operations, including reading characters until a termination character, appending and concatenating strings, converting characters between uppercase and lowercase, comparing strings, and reversing a string. It explains the ASCII representation of characters and the relationship between uppercase and lowercase letters. Each section includes example inputs, outputs, and code snippets to illustrate the concepts.

Uploaded by

nandithamr5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Getchar()

i=0; ch = getchar;// Get a character


while(ch != '*') { str[i] = ch;// Store the read character in str
i++;
ch = getchar();// Get another character }
str[i] = '\0';// Terminate str with null character explain
1. Initialization (i=0):
o The variable i is initialized to 0. This variable serves as an index
to store characters sequentially in the array str.
2. Character Input (ch = getchar();):
o The getchar() function is used to read a single character from the
input (usually from the keyboard or standard input).
3. While Loop (while(ch != '*')):
o The loop continues as long as the character read (ch) is not the
termination character (*).
4. Store Character (str[i] = ch;):
o Each character read by getchar() is stored in the array str at the
current index i.
5. Increment Index (i++):
o The index i is incremented to prepare for storing the next
character in the subsequent iteration.
6. Read Next Character (ch = getchar();):
o The loop reads another character and checks if it is the
termination character (*).
7. Terminate the String (str[i] = '\0';):
o When the loop exits (i.e., the termination character * is
encountered), the null character (\0) is added at the end of the
array. This marks the end of the string in C, making it a valid null-
terminated string.
Example Input and Output:
Input:
Hello World*
Process:
1. getchar() reads characters: H, e, l, l, o, , W, o, r, l, d.
2. Each character is stored sequentially in str.
3. The loop exits when * is read.
4. The null character \0 is added at the end of str.
Final Array (str):
makefile
Copy code
str = "Hello World\0"
Key Notes:
 The array str must have enough space to store all characters entered
by the user before the termination character.
 The null character \0 is crucial to mark the end of the string, ensuring
proper string manipulation later.
 The termination character * is not stored in str.
Append strings

Algorithm: Append Strings


Input:
 destination[]: The string to which another string will be appended.
 source[]: The string to append to the destination string.
Output:
 The destination string contains the original destination string followed
by the source string.

1. Initialize variables:
o Let i = 0 (index for traversing destination).
o Let j = 0 (index for traversing source).
2. Traverse the destination string:
o While destination[i] is not the null character ('\0'):
 Increment i to move to the next character.
o At the end of this step, i points to the null character of the
destination string.
3. Copy characters from the source string:
o While source[j] is not the null character ('\0'):
 Copy source[j] to destination[i].
 Increment both i and j to move to the next positions.
4. Terminate the destination string:
o Assign the null character ('\0') to destination[i].
5. End:
o The destination string now contains its original content followed
by the content of the source string.

Input:
 destination = "Hello, "
 source = "World!"
Steps:
1. Traverse destination to find the null character ('\0').
o i reaches index 7 (end of "Hello, ").
2. Copy characters from source:
o source[0] = 'W' → destination[7] = 'W'
o source[1] = 'o' → destination[8] = 'o'
o ... (continue until source[j] = '\0').
3. Add null character:
o destination[13] = '\0'.
Output:
 destination = "Hello, World!"

Code
#include <stdio.h>

void appendStrings(char destination[], char source[]) {


int i = 0; // Index to traverse destination string
int j = 0; // Index to traverse source string

// Traverse to the end of the destination string


while (destination[i] != '\0') {
i++;
}

// Append characters from source string to destination string


while (source[j] != '\0') {
destination[i] = source[j];
i++;
j++;
}

// Add the null character at the end of the destination string


destination[i] = '\0';
}

int main() {
char str1[100] = "Hello, "; // Destination string with extra space
char str2[] = "World!"; // Source string

printf("Before appending:\n");
printf("String 1: %s\n", str1);
printf("String 2: %s\n", str2);

// Append str2 to str1


appendStrings(str1, str2);

printf("\nAfter appending:\n");
printf("String 1: %s\n", str1);

return 0;
}
ASCII Representation for Uppercase and Lowercase Letters
In ASCII, the alphabetic characters are represented with distinct numeric
codes. Here’s a detailed explanation:
Uppercase Letters (A–Z):
 ASCII codes for uppercase letters range from 65 to 90.
 Each uppercase letter has a unique code.
Lett ASCII Hexadeci
Binary
er Decimal mal

010000
A 65 41
01

010000
B 66 42
10

010000
C 67 43
11

... ... ... ...

010110
Z 90 5A
10

Lowercase Letters (a–z):


 ASCII codes for lowercase letters range from 97 to 122.
 Each lowercase letter has a unique code.
Lett ASCII Hexadeci
Binary
er Decimal mal

011000
a 97 61
01

011000
b 98 62
10

011000
c 99 63
11

... ... ... ...

011110
z 122 7A
10
Relationship Between Uppercase and Lowercase:
 The ASCII code for a lowercase letter is exactly 32 more than its
corresponding uppercase letter.
o Example:
 A → ASCII 65, a → ASCII 97 (65 + 32).
 B → ASCII 66, b → ASCII 98 (66 + 32).

Conversion Formula:
1. Uppercase to Lowercase:
o Add 32 to the ASCII code of the uppercase letter.
o Example: 'A' (65) → 'a' (97) → 65 + 32 = 97.
2. Lowercase to Uppercase:
o Subtract 32 from the ASCII code of the lowercase letter.
o Example: 'a' (97) → 'A' (65) → 97 - 32 = 65.

Convert Characters of a String to Upper Case


Input:
 STR[]: A string containing characters to be converted to uppercase.
Output:
 UPPERSTR[]: A string containing the uppercase version of STR.

Steps:
1. Initialize variables:
o Let I = 0 (index for traversing STR).
o Initialize an empty string UPPERSTR.
2. Traverse each character of the string:
o Repeat Steps 3 and 4 while STR[I] is not the null character ('\0').
3. Check if the character is lowercase:
o If STR[I] is in the range of ASCII values 97 to 122 (i.e., 'a' to 'z'):
 Convert to uppercase by subtracting 32 from the ASCII
value.
 Append the converted character to UPPERSTR.
4. Handle non-lowercase characters:
o If STR[I] is not in the range 97 to 122:
 Append the character STR[I] directly to UPPERSTR.
5. Increment the index:
o Increment I to move to the next character.
6. Terminate the UPPERSTR string:
o Append a null character ('\0') to the end of UPPERSTR.
7. End:
o The UPPERSTR string now contains the uppercase version of STR.

Input:
 STR = "Hello World"
Steps:
1. Initialize I = 0 and UPPERSTR = "".
2. Traverse each character of STR:
o STR[0] = 'H' → Already uppercase → UPPERSTR = "H".
o STR[1] = 'e' → Lowercase → Convert to E → UPPERSTR = "HE".
o ... (continue for all characters).
3. Append null character ('\0').
4. Output: UPPERSTR = "HELLO WORLD".
#include <stdio.h>

int main() {
char lower = 'a';
char upper = 'A';

// Convert lowercase to uppercase


char convertedToUpper = lower - 32;
printf("Lowercase '%c' converted to Uppercase: '%c'\n", lower,
convertedToUpper);

// Convert uppercase to lowercase


char convertedToLower = upper + 32;
printf("Uppercase '%c' converted to Lowercase: '%c'\n", upper,
convertedToLower);

return 0;
}

Algorithm to Concatenate Two Strings


Input: Two strings, s1 and s2.
Output: A new string new_str that contains the concatenation of s1 and s2.

Steps:
1. Initialize Counters: Set i = 0 and j = 0.
2. Copy First String:
o While s1[i] is not the null character ('\0'):
 Copy s1[i] to new_str[i].
 Increment i.
3. Copy Second String:
o While s2[j] is not the null character ('\0'):
 Copy s2[j] to new_str[i].
 Increment i and j.
4. Terminate the New String:
o Append a null character ('\0') to new_str at position i.
5. Output: new_str now contains the concatenated result of s1 and s2.

Example Code in C
#include <stdio.h>

void concatenate(char s1[], char s2[], char new_str[]) {


int i = 0, j = 0;

// Copy first string to new_str


while (s1[i] != '\0') {
new_str[i] = s1[i];
i++;
}

// Copy second string to new_str


while (s2[j] != '\0') {
new_str[i] = s2[j];
i++;
j++;
}

// Append null character


new_str[i] = '\0';
}

int main() {
char s1[] = "Hello, ";
char s2[] = "World!";
char new_str[50]; // Ensure it's large enough to hold the concatenated
string

// Concatenate the strings


concatenate(s1, s2, new_str);

// Output the result


printf("Concatenated String: %s\n", new_str);

return 0;
}

Explanation of Code:
1. String Initialization:
o s1 contains "Hello, ".
o s2 contains "World!".
o new_str is declared as an empty array to hold the concatenated
result.
2. Concatenation Process:
o Characters from s1 are copied into new_str first.
o Characters from s2 are then appended to new_str.
3. Final Termination:
o A null character ('\0') is added at the end to ensure new_str is a
valid string.

Output:
Concatenated String: Hello, World!

Algorithm to Compare Two Strings


Input: Two strings, S1 and S2.
Output: Determines if the strings are equal, if S1 > S2, or if S1 < S2.

Steps:
1. Check String Lengths:
o If the lengths of S1 and S2 are not equal, directly conclude that
the strings are not equal and check which one is
lexicographically larger.
2. Initialize Variables:
o Set i = 0 and same = 1.
3. Character-by-Character Comparison:
o While both S1[i] and S2[i] are not null ('\0'):
 If S1[i] != S2[i], set same = 0 and break the loop.
4. Check Lexicographical Order:
o If same == 0:
 Compare S1[i] and S2[i]:
 If S1[i] > S2[i], S1 > S2.
 If S1[i] < S2[i], S1 < S2.
5. Output:
o If same == 1, the strings are equal.
o Otherwise, output which string precedes the other
lexicographically.

Example Code in C
#include <stdio.h>

void compareStrings(char S1[], char S2[]) {


int i = 0, same = 1;

// Compare character by character


while (S1[i] != '\0' && S2[i] != '\0') {
if (S1[i] != S2[i]) {
same = 0;
break;
}
i++;
}

// Check lengths if characters are equal so far


if (S1[i] != '\0' || S2[i] != '\0') {
same = 0;
}

// Print the result


if (same) {
printf("The strings are equal.\n");
} else if (S1[i] > S2[i]) {
printf("String S1 is lexicographically greater than S2.\n");
} else {
printf("String S1 is lexicographically less than S2.\n");
}
}

int main() {
char S1[] = "apple";
char S2[] = "apples";

// Compare strings
compareStrings(S1, S2);

return 0;
}

Explanation of Code:
1. String Comparison:
o The while loop iterates through both strings simultaneously.
o Characters are compared one by one.
2. Handle Mismatches:
o If any mismatch is found, the loop exits, and same is set to 0.
3. Lexicographical Order:
o If characters differ, the code determines if S1 > S2 or S1 < S2
based on their ASCII values.
4. Handle Unequal Lengths:
o If one string ends before the other, the strings are unequal, and
the comparison is based on which one ends first.
Output Examples:
Example 1:
Input:
char S1[] = "apple";
char S2[] = "apple";
Output:
The strings are equal.
Example 2:
Input:
char S1[] = "apple";
char S2[] = "apples";
Output:
String S1 is lexicographically less than S2.
Example 3:
Input:
char S1[] = "banana";
char S2[] = "apple";
Output:
String S1 is lexicographically greater than S2.
Algorithm to Reverse a String
Input: A string S1.
Output: Reversed string S1 (in place).

Steps:
1. Initialize Pointers:
o Set i = 0 (points to the first character).
o Set j = length of S1 - 1 (points to the last character).
2. Traverse the String:
o Use a while loop that runs until i < j:
 Swap the characters at positions i and j.
 Increment i to move forward.
 Decrement j to move backward.
3. Output:
o Once the loop completes, the string S1 is reversed in place.

Example Code in C
#include <stdio.h>
#include <string.h>

void reverseString(char S1[]) {


int i = 0, j = strlen(S1) - 1;
char temp;

// Swap characters from the start and end


while (i < j) {
temp = S1[i];
S1[i] = S1[j];
S1[j] = temp;
i++;
j--;
}
}

int main() {
char S1[] = "HELLO";

// Reverse the string


reverseString(S1);

// Print the reversed string


printf("Reversed String: %s\n", S1);

return 0;
}

Explanation of Code:
1. String Traversal:
o The while loop iterates until i < j. This ensures characters from
the front and back are swapped until the middle is reached.
2. Character Swap:
o Characters at positions i and j are swapped using a temporary
variable temp.
3. Update Pointers:
o Increment i to move forward.
o Decrement j to move backward.
4. Reversal Complete:
o Once the loop exits, the string is reversed.

Example:
Input:
char S1[] = "HELLO";
Output:
Reversed String: OLLEH

1. Extracting a Substring from the Left


Algorithm:
1. Initialize:
o Set I = 0.
2. Repeat while STR[I] != NULL AND I < N:
o Copy STR[I] to Substr[I].
o Increment I.
3. Append null character:
o Set Substr[I] = NULL.
4. Exit.
Basic Code Example (C):
void Substr_Left(char STR[], char Substr[], int N) {
int I = 0;
while (STR[I] != '\0' && I < N) {
Substr[I] = STR[I];
I++;
}
Substr[I] = '\0';
}
2. Extracting a Substring from the Right
Algorithm:
1. Initialize:
o Set I = 0, J = Length(STR) - N.
2. Repeat while STR[J] != NULL:
o Copy STR[J] to Substr[I].
o Increment I and J.
3. Append null character:
o Set Substr[I] = NULL.
4. Exit.
Basic Code Example (C):
void Substr_Right(char STR[], char Substr[], int N) {
int I = 0, J = strlen(STR) - N;
while (STR[J] != '\0') {
Substr[I] = STR[J];
I++;
J++;
}
Substr[I] = '\0';
}
3. Extracting a Substring from the Middle
Algorithm:
1. Initialize:
o Set I = Position, Sub_I = 0.
2. Repeat while Length > 0 AND STR[I] != NULL:
o Copy STR[I] to Substr[Sub_I].
o Increment I and Sub_I.
o Decrement Length.
3. Append null character:
o Set Substr[Sub_I] = NULL.
4. Exit.
Basic Code Example (C):
void Substr_Middle(char STR[], char Substr[], int Position, int Length) {
int I = Position, Sub_I = 0;
while (Length > 0 && STR[I] != '\0') {
Substr[Sub_I] = STR[I];
Sub_I++;
I++;
Length--;
}
Substr[Sub_I] = '\0';
}
4. Reversing a String
Algorithm:
1. Initialize:
o Set I = 0, J = Length(STR) - 1.
2. Repeat while I < J:
o Swap STR[I] with STR[J].
o Increment I and decrement J.
3. Exit.
Basic Code Example (C):
void Reverse_String(char STR[]) {
int I = 0, J = strlen(STR) - 1;
char temp;
while (I < J) {
temp = STR[I];
STR[I] = STR[J];
STR[J] = temp;
I++;
J--;
}
}

5. Inserting a String into Another String


Algorithm:
1. Initialize:
o Set I = 0, New_I = 0.
2. Repeat while T[I] != NULL:
o If New_I == Position:
 Copy all characters of S into NEW_STR.
o Else:
 Copy T[I] into NEW_STR[New_I].
o Increment I and New_I.
3. Append null character:
o Set NEW_STR[New_I] = NULL.
4. Exit.

Basic Code Example (C):


void Insert_String(char T[], char S[], char NEW_STR[], int Position) {
int I = 0, New_I = 0;
while (T[I] != '\0') {
if (New_I == Position) {
int J = 0;
while (S[J] != '\0') {
NEW_STR[New_I] = S[J];
New_I++;
J++;
}
}
NEW_STR[New_I] = T[I];
New_I++;
I++;
}
NEW_STR[New_I] = '\0';
}
6. Extracting Characters from the End
Algorithm:
1. Initialize:
o Set I = Length(STR) - 1, Sub_I = 0.
2. Repeat while Sub_I < N:
o Copy STR[I] to Substr[Sub_I].
o Decrement I and increment Sub_I.
3. Reverse Substr to correct the order.
4. Append null character:
o Set Substr[Sub_I] = NULL.
5. Exit.
Basic Code Example (C):
void Extract_End(char STR[], char Substr[], int N) {
int I = strlen(STR) - 1, Sub_I = 0;
while (Sub_I < N) {
Substr[Sub_I] = STR[I];
I--;
Sub_I++;
}
Substr[Sub_I] = '\0';
Reverse_String(Substr); // Reverse to get proper order
}

You might also like