Apex - 字串



Apex中的字串,與任何其他程式語言一樣,是任何一組字元,沒有字元限制。

示例

String companyName = 'Abc International';
System.debug('Value companyName variable'+companyName);

字串方法

Salesforce中的String類有很多方法。本章將介紹一些最重要和最常用的字串方法。

contains

如果給定字串包含提到的子字串,則此方法將返回true。

語法

public Boolean contains(String substring)

示例

String myProductName1 = 'HCL';
String myProductName2 = 'NAHCL';
Boolean result = myProductName2.contains(myProductName1);
System.debug('O/p will be true as it contains the String and Output is:'+result);

equals

如果給定字串和方法中傳遞的字串具有相同的字元二進位制序列並且它們不為空,則此方法將返回true。您也可以使用此方法比較SFDC記錄ID。此方法區分大小寫。

語法

public Boolean equals(Object string)

示例

String myString1 = 'MyString';
String myString2 = 'MyString';
Boolean result = myString2.equals(myString1);
System.debug('Value of Result will be true as they are same and Result is:'+result);

equalsIgnoreCase

如果stringtoCompare的字元序列與給定字串相同,則此方法將返回true。但是,此方法不區分大小寫。

語法

public Boolean equalsIgnoreCase(String stringtoCompare)

示例

以下程式碼將返回true,因為字串字元和序列相同,忽略大小寫。

String myString1 = 'MySTRING';
String myString2 = 'MyString';
Boolean result = myString2.equalsIgnoreCase(myString1);
System.debug('Value of Result will be true as they are same and Result is:'+result);

remove

此方法將從給定字串中刪除stringToRemove中提供的字串。當您想要從字串中刪除一些特定字元並且不知道要刪除的字元的確切索引時,這很有用。此方法區分大小寫,如果字元序列相同但大小寫不同,則不起作用。

語法

public String remove(String stringToRemove)

示例

String myString1 = 'This Is MyString Example';
String stringToRemove = 'MyString';
String result = myString1.remove(stringToRemove);
System.debug('Value of Result will be 'This Is Example' as we have removed the MyString 
   and Result is :'+result);

removeEndIgnoreCase

此方法從給定字串中刪除stringToRemove中提供的字串,但僅當它出現在末尾時。此方法不區分大小寫。

語法

public String removeEndIgnoreCase(String stringToRemove)

示例

String myString1 = 'This Is MyString EXAMPLE';
String stringToRemove = 'Example';
String result = myString1.removeEndIgnoreCase(stringToRemove);
System.debug('Value of Result will be 'This Is MyString' as we have removed the 'Example'
   and Result is :'+result);

startsWith

如果給定字串以方法中提供的指定字首開頭,則此方法將返回true。

語法

public Boolean startsWith(String prefix)

示例

String myString1 = 'This Is MyString EXAMPLE';
String prefix = 'This';
Boolean result = myString1.startsWith(prefix);
System.debug(' This will return true as our String starts with string 'This' and the 
   Result is :'+result);
廣告