Skip to content

C C strings Tutorial with Examples

John Hau edited this page Mar 25, 2022 · 1 revision

1- C-Style String

1.1- String In C++ there are two types of strings, C-style strings, and C++-Style strings. C-style strings are really arrays, but there are some different functions that are used for strings, like adding to strings, finding the length of strings, and also of checking to see if strings match. The definition of a string would be anything that contains more than one character strung together. For example, "This" is a string. However, single characters will not be strings, though they can be used as strings. Strings are arrays of chars. String literals are words surrounded by double quotation marks.

// Declare a C-Style String. char mystring[] = { 't', 'h', 'i', 's', ' ', 'i', 's' ,' ', 't', 'e', 'x', 't', '\0'};

// This is a string literal. char mystring[] = "this is text''; StringLiteralExample.cpp

#include <stdio.h>

int main() {

// Declare a String literal. char s1[] = "What is this";

// Print out the string printf("Your string = %s", s1);

fflush(stdout);

return 0; }

image

image

image

StringFunctionsExample.cpp

#include <stdio.h>

// Using string library. #include <string.h>

int main() {

// Declare a string literal. char s1[] = "This is ";

// Declare a C-Style string // (With null character at the end). char s2[] = { 't', 'e', 'x', 't', '\0' };

// Function: size_t strlen(const char *str) // strlen funtion return length of the string. // site_t: is unsigned integer data type. size_t len1 = strlen(s1); size_t len2 = strlen(s2);

printf("Length of s1 = %d \n", len1); printf("Length of s2 = %d \n", len2);

// Declare an array with 100 elements. char mystr[100];

// Function: char *strcpy(char *dest, const char *src) // copy s1 to mystr. strcpy(mystr, s1);

// Function: char *strcat(char *dest, const char *src) // Using strcat function to concatenate two strings strcat(mystr, s2);

// Print out content of mystr. printf("Your string = %s", mystr);

fflush(stdout);

return 0;

}

image

image

image

image

image

image

image

image

image

image

image

image

image

image

image

2.2.7- upper/lower Although in string class does not give you a method to convert a string into uppercase or lowercase string, but you can do it with other libraries in C++. Using transform function of namespace std: UpperLowerDemo1.cpp

#include #include #include

using namespace std;

int main() {

string str = "This is text";

cout << "- str= " << str << endl;

cout << " ----------------"  << endl;

// Convert to uppercase
std::transform(str.begin(), str.end(),str.begin(), ::toupper);


cout << "- str= " << str << endl;

// Reset str
str =  "This is text";

cout << " -------------- " << endl;

// Convert to lowercase.
std::transform(str.begin(), str.end(),str.begin(), ::tolower);

cout << "- str= " << str << endl;

}

image

Clone this wiki locally