函数式编程 - 字符串


字符串是一组包含空格的字符我们可以说它是一个以 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 中的字符串

以下程序是一个示例,展示了如何在 Erlang(一种函数式编程语言)中创建字符串。

-module(helloworld).  
-export([start/0]).   
start() -> 
   Str = "Today is: Holiday",  
   io:fwrite("~p~n",[Str]). 

它将产生以下输出 -

"Today is: Holiday" 

C++ 中的字符串操作

不同的编程语言支持不同的字符串方法。下表显示了 C++ 支持的一些预定义字符串方法。

编号 方法及说明
1

结构体(s1,s2)

它将字符串 s2 复制到字符串 s1

2

Strcat(s1,s2)

它将字符串 s2 添加到 s1 的末尾

3

斯特伦(s1)

它提供了字符串 s1 的长度

4

Strcmp(s1,s2)

当字符串 s1 和 s2 相同时返回 0

5

Strchr(s1,ch)

它返回一个指向字符串 s1 中第一次出现字符 ch 的指针

6

strstr(s1,s2)

它返回一个指向字符串 s1 中第一次出现字符串 s2 的指针

以下程序显示了如何在 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 中的字符串操作

下表显示了 Erlang 支持的预定义字符串方法的列表。

编号 方法及说明
1

长度(s1)

返回给定字符串中的字符数。

2

等于(s1,s2)

当字符串 s1 和 s2 相等时返回 true,否则返回 false

3

连接(s1,s2)

它将字符串 s2 添加到字符串 s1 的末尾

4

字符串(s1,ch)

返回字符串 s1 中字符 ch 的索引位置

5

字符串 (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"