![]() |
C/C++, KDEVELOP |
|---|
BasicsProgram FlowFunctionsClasses and ObjectsX WindowKDevelop----------------- © Alfred Nussbaumer Updated: 09 December 2021 ----------------- |
Character StringsThe char type may be used for integer values and for single literals: char c = 'x'; char a = 3; A character string is a series of one or more chracters ending with the null character (ASCII 0); double quotes are used for the string: #define NAME "A.Nussbaumer" The following syntax is used for string variables: char path[] = "public_html/c++";The square brackets denotes that path is an array of multiple characters ending with a null character. You may specify the string's size: char firstname[50]; ExampleThe following example demonstrates the usage of input and output and how to find the length of a string: #include <iostream.h>
#include <string.h>
char name[50];
main() {
cout << "Tell me your name... ";
cin >> name;
cout << "Hi " << name << '!' << endl;
cout << "length: " << strlen(name) << endl;
return 0;
}
Here is a sample run: alfred@duron:~/cpp> g++ inout.cpp -o inout alfred@duron:~/cpp> ./inout Tell me your name... Alfred Hi Alfred! length: 6 alfred@duron:~/cpp> Searching for SubstringsThe function strstr(str1, str2) returns a pointer to the first occurence of the string str2. The header file string.h is required.
#include <iostream.h>
#include <string.h>
int main() {
char yourstring[100] = "Linux is cool";
cout << strstr(yourstring, "cool") << endl;
}
cool Concatenating StringsThe function strcat(str1, str2) concatenates str1 and str2 (the header file string.h is required). #include <iostream.h>
#include <string.h>
int main() {
char w1[7] = "Linux ";
char w2[4] = "is ";
char w3[6] = "cool ";
char resultstring[128]="";
strcat(resultstring, w1);
strcat(resultstring, w2);
strcat(resultstring, w3);
cout << resultstring << endl;
}
Linux is cool |