Functional-programming-strings

提供:Dev Guides
移動先:案内検索

関数型プログラミング-文字列

*string* は、スペースを含む文字のグループです。 NULL文字(「\ 0」)で終わる文字の1次元配列であると言えます。 文字列は、C、C ++、Java、PHP、Erlang、Haskell、Lispなどのほとんどのプログラミング言語でサポートされている定義済みクラスと見なすこともできます。

次の画像は、文字列「チュートリアル」がメモリ内でどのように表示されるかを示しています。

文字列

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 ++での文字列操作

異なるプログラミング言語は、文字列の異なるメソッドをサポートします。 次の表は、C ++でサポートされるいくつかの定義済みの文字列メソッドを示しています。

S.No. Method & Description
1

Strcpy(s1,s2)

文字列s2を文字列s1にコピーします

2

Strcat(s1,s2)

s1の末尾に文字列s2を追加します

3

Strlen(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でサポートされている事前定義された文字列メソッドのリストを示しています。

S.No. Method & Description
1

len(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"