Hot answers tagged

50

The separator string used in the split method is a regular expression and "." is a special character in regular expressions. The regular expression for a literal "." is "\." However "\" is also used to escape characters when expressing Strings in Apex, and so this character too needs escaping: String[] cd = createDate.split('\\.'); The documentation ...


48

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 docuentations says: Returns true if the specified String is white space, empty (''), or null; otherwise, returns false.


26

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]|...


19

Per RestRequest methods, if the function accepts parameters, it will be deserialized into the provided parameters, otherwise it will be in RestRequest.requestBody. The solution, then, is to make sure your function takes no parameters. If the Apex method has no parameters, then Apex REST copies the HTTP request body into the RestRequest.requestBody ...


19

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....


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)[...


13

In order to be able to retrieve data in this way, your method needs to be a getter, as there's an implicit 'get' added by Visualforce. You don't need a way to set it as you aren't binding any inputs to it. There's also no reason to use an apex:repeat, as this is for iterating a collection (though I think that it would work with a single value). You can ...


13

The option to replace case insensitive regex in java is Pattern.CASE_INSENSITIVE, which can also be specified as (?i) (http://boards.developerforce.com/t5/Apex-Code-Development/Why-Pattern-CASE-INSENSITIVE-not-detectable/td-p/204337) String srcStr = '{!id} value {!Id} is not {!ID}'; String replaceToken = '(?i)\\{!id\\}'; System.debug('REPLACEMENT ' + ...


13

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 ...


13

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 ...


12

It depends what you mean by "such that each of its characters can be manipulated". Apex Strings (as in Java) are immutable, so a true manipulation of the source value is not going to happen. Nor is there a char datatype in Apex. You can inspect individual "chars" by using the String.mid method, or you can efficiently create an array of 1-char long Strings ...


12

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.


12

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 ...


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


12

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);


12

I like using normalizeSpace() instead of trim() for such scenarios, as it also handles of 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 ...


12

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'


11

Typically it's best to leave the formatting to the visualforce page and leave the controller to handle the model/controller side of things. You can easily do this in the Visualforce page and if you're using it in a lot of places just put it in a component you can reference all over the place. <apex:outputText value="{0, number, ###,###,###}" rendered="{!...


11

Try using string.valueOf(variableName); That should solve your problem.


10

Have you tried Date.parse()? From the documentation: Constructs a Date from a String. The format of the String depends on the local date format. The following example works in some locales: date mydate = date.parse('12/27/2009');


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

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


9

Strings are immutable which means that they cannot be modified. When you call an instance operation on a String it creates a new String instance to return. You need to assign the result to another variable (or to the variable itself). For example: Descrip = Descrip.replace(string.valueOf(oEvtOwnrs.get(ev.WhatID))), string.valueOf(nEvtOwnrs.get(ev....


9

You can use the mode modifier (?m) at the beginning of your regex pattern to specify the multiline option. String testString = 'Line 1: Does not match\nCustomer Name: Bob Dole'; String regex = '(?m)^\\s*Customer Name\\s*:\\s+(.*)$'; Matcher m = Pattern.compile(regex).matcher(testString); // iterate through testString finding subsequent matches while (m....


9

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,...


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.


9

I will answer to my own question : String text = 'ILikeSalesforcePlatform'; text = String.valueOf(text.splitByCharacterTypeCamelCase()).replaceAll('[\\,\\(\\)]',''); System.debug(text); Output : USER_DEBUG|[3]|DEBUG|I Like Salesforce Platform


9

Something like : String s = '(09890)'; Integer i = Integer.valueOf(s.replaceAll('[\\(\\)]',''));


9

Technically, since you're passing the value as a String already, you probably don't need to query the value at all: TM.Meeting__c = ApexPages.currentPage().getParameters().get('EventId'); However, say you wanted to validate the value first, to make sure the user can see it (so they're not just faking a value), you could do this: String eventId = ApexPages....


9

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 ...


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