字符串是一组包含空格的字符,我们可以说它是一维字符数组,以NULL字符(\\0)结尾。字符串也可以视为预定义的类,大多数编程语言都支持该类,如C,C++,Java,PHP,Erlang,Haskell,Lisp等。
下图显示了字符串" Tutorial"在内存中的外观。
下面的程序是一个示例,显示了如何使用C ++创建字符串,C ++是一种面向对象的编程语言。
#include <iostream> using namespace std; int main () { char greeting[20] = {'H', 'o', 'l', 'i', 'd', 'a', 'y', '\0'}; cout << "Today is: "; cout << greeting << endl; return 0; }
它将产生以下输出-
Today is: Holiday
以下程序是一个示例,显示了如何在Erlang(一种函数编程语言)中创建字符串。
-module(helloworld). -export([start/0]). start() -> Str = "Today is: Holiday", io:fwrite("~p~n",[Str]).
它将产生以下输出-
"Today is: Holiday"
不同的编程语言在字符串上支持不同的方法。下表显示了C ++支持的一些预定义的字符串方法。
S.No. | Method & 描述 |
---|---|
1 | Strcpy(s1,s2) 它将字符串s2复制到字符串s1中 |
2 | Strcat(s1,s2) 它将字符串s2添加到s1的末尾 |
3 | Strlen(s1) 它提供字符串s1的长度 |
4 | Strcmp(s1,s2) It returns 0 when string s1 & s2 are same |
5 | Strchr(s1,ch) 它返回指向字符串s1中字符ch的第一个出现的指针 来源:LearnFk无涯教程网 |
6 | Strstr(s1,s2) 它返回一个指向字符串s1在字符串s1中首次出现的指针 |
以下程序显示了如何在C ++中使用上述方法-
#include <iostream> #include <cstring> using namespace std; int main () { char str1[20] = "Today is "; char str2[20] = "Monday"; char str3[20]; int len ; strcpy( str3, str1); //copy str1 into str3 cout << "strcpy( str3, str1) : " << str3 << endl; strcat( str1, str2); //concatenates str1 and str2 cout << "strcat( str1, str2): " << str1 << endl; len = strlen(str1); //String length after concatenation cout << "strlen(str1) : " << len << endl; return 0; }
它将产生以下输出-
strcpy(str3, str1) : Today is strcat(str1, str2) : Today is Monday strlen(str1) : 15
下表显示了Erlang支持的预定义字符串方法的列表。
S.No. | Method & 描述 |
---|---|
1 | len(s1) 它将字符串s2提供给字符串s1 |
2 | equal(s1,s2) 当字符串s1和s2相等时返回true,否则返回false |
3 | concat(s1,s2) 它在字符串s1的末尾添加字符串s2 |
4 | str(s1,ch) 返回字符串s1中字符ch的索引位置 |
5 | str(s1,s2) 它返回字符串s1中s2的索引位置 |
6 | substr(s1,s2,num) 此方法根据起始位置和起始位置的字符数从字符串s1返回字符串s2 |
7 | to_lower(s1) 此方法以小写形式返回字符串 |
以下程序显示了如何在Erlang中使用上述方法。
-module(helloworld). -import(string,[concat/2]). -export([start/0]). start() -> S1 = "Today is ", S2 = "Monday", S3 = concat(S1,S2), io:fwrite("~p~n",[S3]).
它将产生以下输出-
"Today is Monday"
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)