Hot answers tagged

73

I use the isBlank(String) method on the string class in order to check whether a string is either null, white space or empty. String.isBlank(record.txt_Field__c); The documentation says: Returns true if the specified String is white space, empty (''), or null; otherwise, returns false.


30

Use String.split(regExp, limit) method: Documentation says Returns a list that contains each substring of the String that is terminated by either the regular expression regExp or the end of the String. Example: String str = 'this-is-test-data'; List<String> res = str.split('-', 2); System.debug(res); Result: 15:16:58:001 USER_DEBUG [3]|...


24

As an indicator to the user that the string has been shortened, also adding '...' to the end can be helpful. There is a String method that does that: String newString = sizeString.abbreviate(120); This example from the help illustrates how the length of the '...' is also considered: String s = 'Hello Maximillian'; String s2 = s.abbreviate(8); System....


19

Not a catch per say (IIRC you cannot catch it, especially if Catch Exception did not work) but will solve the problem of regex to complex, use a custom iterator: CLASS public with sharing class Utility_RowIterator implements Iterator<String>, Iterable<String> { private String m_Data; private Integer m_index = 0; private String ...


17

I like using normalizeSpace() instead of trim() for such scenarios, as it also handles repeated white space. normalizeSpace() Returns the current String with leading, trailing, and repeating white space characters removed. String s1 = ' Salesforce \t force.com '; String s2 = s1.normalizeSpace(); System.assertEquals( 'Salesforce force.com', ...


16

use trim() method of String class Returns a copy of the string that no longer contains any leading or trailing white space characters. String s1 = ' Hello! '; String trimmed = s1.trim(); System.assertEquals('Hello!', trimmed);


16

One option is to use the substringBefore and substringAfter methods. String delimiter = '-'; String input = 'this-is-test-data'; String firstSplit = input.substringBefore(delimiter); // 'this' String lastSplits = input.substringAfter(delimiter); // 'is-test-data'


16

String.isEmpty is marginally faster (~0.00219ms vs ~0.00206ms, about 6%). This is such a trivially small amount that there's no reason to worry about which one you use from a performance perspective. Practically speaking, you should generally use String.isBlank if you expect potentially whitespace strings (e.g. from user input that may be all whitespace), ...


16

Yes. Collection membership is case sensitive. This applies to Sets: If the set contains String elements, the elements are case-sensitive. Two set elements that differ only by case are considered distinct. and to Maps: Map keys of type String are case-sensitive. Two keys that differ only by the case are considered unique and have corresponding ...


14

You're calling String.valueOf() on the Event Sobject itself, not the Id string. As written, your first line should be: EventIdString = String.valueOf( [select id from Event where Id=: (ApexPages.currentPage().getParameters().get('EventId'))].Id); But you don't even need to use String.valueOf(). ID can be directly cast to String: EventIdString = (String)[...


14

How about: String pageName = ApexPages.currentPage().getUrl().substringBetween('apex/', '?'); or, if you do not have parameters: String pageName = ApexPages.currentPage().getUrl().substringAfter('apex/'); Check out the other String methods, there are lots to help in this regard.


14

Use String.isBlank(yourString) to check if it's null or '' or ' '. This method detects whether string has null or blank space or just quotes. Example: String str = 'searchValue'; System.assertEquals(false,String.isBlank(str)); // returns false since string is not blank


13

The String class has several static utility methods to transform a value into its string representation, like this: String.valueOf(variableName); That should solve your problem.


13

I'd expect this code to crash, because ActivityDate can be null, which means that tsk.ActivityDate.format() should throw a NullPointerException. I can demonstrate this through the following code: Task t = [select ActivityDate from Task where ActivityDate = null limit 1]; system.debug(t.ActivityDate.format()); You do end up eventually checking for a null ...


13

This is a newer revision of Adrian Larson's previous answer for benchmark comparison. This should work quite well for short-ish text fields quite well at the expense of some bytes of heap. For a longer text field, it takes longer. Long story short, if you have very limited heap space (or disk space), it might make sense to use Adrian's method. Also, if ...


12

The difference is slight between isEmpty() and isBlank() isBlank(inputString): Returns true if the specified String is white space, empty (''), or null; otherwise, returns false. isEmpty(inputString) : Returns true if the specified String is empty ('') or null; otherwise, returns false. So the isEmpty() function is a subset of isBlank() function. Usage ...


12

IsNumeric() method works for only Integer value not for decimal value like this String str = '10'; system.debug('===strToDec=='+str.isNumeric()); This will return true. String str = '10.25'; Decimal strToDec = decimal.valueOf(str); system.debug('===strToDec=='+strToDec); String decToStr = String.valueOf(strToDec); system.debug('===decToStr=='+...


12

This is a good time for replaceAll(regex, replacement): String testString = 'Line 1\r\nLine 2\r\n\r\nLine 3'; system.debug(testString.replaceAll('(\\r|\\n)+', ' ** ')); Results: Line 1 ** Line 2 ** Line 3


11

This is how this is done System.debug(LoggingLevel.INFO,String.format('\'{\'{0}\'}\'', new String[] { String.valueOf(777) })); produces {777} SFDC String.format (also used by VF apex:outputtext) uses the Java MessageFormat class. And braces are escaped by enclosing in single quotes, which in apex must also be escaped by backslash. See https://...


11

You can use the String.split() method, using '' (two single quotes) as a parameter:: String ourString = 'Salesforce SE'; String[] stringCharacters = ourString.split(''); System.debug(stringCharacters); // stringCharacters is a List<String>, each element being a substring of length 1: // (,S,a,l,e,s,f,o,r,c,e, ,S,E) Note that the first element in the ...


10

In this case the best approach is going to be to overload the method, as Apex doesn't have any concept of optional parameters. So to illustrate, your class might look like this: public void myMethod(String input1, String input2) { System.debug(input1); System.debug(input2); } public void myMethod(String input1) { myMethod(input1, 'DEFAULT ...


10

It sounds like your exception is encountered not by the response, but by Apex code mimicking it? The response format is correct: the backslash \ is correctly placed to permit a " in the JSON. Check it out, if I put your string, literally, as plaintext into something returnable by an Apex function: <apex:page contentType="text/plain">{"MessageSeq":13,...


10

The String.startsWith method is case sensitive. However there is a String.startsWithIgnoreCase method which as the name notes is case insensitive.


10

Split in Apex is very similar to Java string split. the pattern you pass to the split method is not a direct match, its a REGEX pattern. so the pipe symbol | is considered as a Regex input and it splits the string into individual characters. You can use the below code to get thru this newString.split('\\|') here's some other discussions around the same ...


10

Someone has already published a complete solution. You just need to translate this answer from Javascript to Apex. The author of that answer credits this post, which was posted by lehel on May 6, 2011 and archived in 2012. I can't testify to the completeness, but here's the translation: public class Accents { public static String removeDiacritics(String ...


10

I suppose you could make your own isNumeric() method to also cover decimal values: public class StringUtilities{ public static Boolean isNumeric(String s){ Boolean ReturnValue; try{ Decimal.valueOf(s); ReturnValue = TRUE; } catch (Exception e) { ReturnValue = FALSE; } return ...


10

The simplest solution is to use the \W character as your entire expression, it matches any non-word character. Unfortunately, this solution would also match any whitespace characters, and ignore the underscore character (_). Here's the expression I would use: (_|[^\w\s]) What does it mean? 1st Capturing Group (_|[^\w\s]) Matches either alternative 1st ...


10

You can match all punctuation using \\p{Punct}, as mentioned in the Pattern class, which matches: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ For example, the following code results in an empty String: String s = '~!@#$%^*()_+|}{":?><`=;/.,][-\'\\'; System.debug(s.replaceAll('\\p{Punct}','')); Note that the "escapes" are not disappearing, they're ...


10

In Apex Code, null actually doesn't count as any bytes (per se). However, when you add null to a string, it's typed coerced into a string four-characters long-- "null". This behavior seems to be rather specific to Apex Code. In other languages that allow null bytes in a string, null should actually be one byte long. I was going to say something about UTF-8 ...


9

You need to turn the digest bytes into a valid string first and one way to do that is to base64 encode: Blob b = Crypto.generateDigest('SHA-256', Blob.valueOf(valueToHash)); sfMessage.Hashed_String__c = EncodingUtil.base64Encode(b); You will have to do the base 64 decode before using the digest too. See EncodingUtil.


Only top voted, non community-wiki answers of a minimum length are eligible