Join an array of strings in Apex - salesforce

Using Apex, I want to split a string and then rejoin it with the 'AND' operator as the separator.
I split the string successfully but having an issue in rejoining it.
String [] ideaSearchText = searchText.Split(' ');
// How to rejoin the array of strings with 'AND'?
How can I do this?

You can do this as of v26 (Winter 13) by passing your String[] to String.join().
String input = 'valueOne valueTwo valueThree';
String[] values = input.split(' ');
String result = String.join( values, ' AND ' );
Anonymous Apex output calling System.debug(result):
21:02:32.039 (39470000)|EXECUTION_STARTED
21:02:32.039 (39485000)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
21:02:32.040 (40123000)|SYSTEM_CONSTRUCTOR_ENTRY|[3]|<init>()
21:02:32.040 (40157000)|SYSTEM_CONSTRUCTOR_EXIT|[3]|<init>()
21:02:32.040 (40580000)|USER_DEBUG|[5]|DEBUG|valueOne AND valueTwo AND valueThree

Note if the string object is too large you will get the exception Regex too complicated. In this case you can do something like the following:
Blob blobValue = (Blob)record.get(blobField);
// Truncate string then split on newline, limiting to 11 entries
List<String> preview = blobValue.toString().substring(0,1000).split('\n', 11);
// Remove the last entry, because The list’s last entry contains all
// input beyond the last matched delimiter.
preview.remove(preview.size()-1);
// In my use-case, I needed to return a string, and String.join() works
// as the reverse of split()
return String.join(preview, '\n');

Related

Get the comma separated list from an array

I have a function which has a return type of IList<Product>
class Product
{
int Id,
string ProductClass,
string ProductName
}
I have to make a comma separated string of ProductName. I am trying below code but it is not giving me correct result
Array arrayofProduct = MyFunction().ToArray();
string productNames = string.Join(",", arrayofProduct);
I think it is because arrayofProduct has 3 columns and I have to pass only 1 (i.e. ProductName) to get the comma separated list.
Use Linq to Select the ProductName into a collection and then use that to construct the desired comma separated string
var names = MyFunction().Select(p => p.ProductName);
string productNames = string.Join(",", names);
Or apart from the above answer you can directly query your array of product and get the result.
string productNames = string.Join(",", arrayofProduct.Select(x => x.ProductName);

Add Single quotes where string contains comma in AngularJS

I have a string which contains values like
var string = A,B,C
Here I want to add single quote for each comma value, expected result should be as below
output = 'A','B','C'
My angular code is
var data = {
output : this.string.split("\',"),
}
which is giving result as
["A,B,C"]
Could anyone please help on this how can I get desired output.
I am understanding your code as
var string = "A,B,C"; // because string should be in this format.
and you just need to replace "\'," from your split function to "," which will give you an array like this
var out = string.split(",");
console.log(out);
[ 'A', 'B', 'C' ] // this is the output.
as split function searches for the given expression and split the string into array.
but if you just want to modify the string without making it in array then you can use the below trick
var out = "'" + string.replace(/,/g, "','") + "'";
console.log(out);
'A','B','C' // result as u mentioned and this is of string type.

Capitalize a cyrillic strings with JavaScript

I'm making an AngularJS filter which capitalizes each word's first letter.
It works well with a-zA-Z letters, but in my case I use also cyrillic characters and I would like to make it work.
var strLatin = "this is some string";
var strCyrillic = "това е някакъв низ";
var newLatinStr = strLatin.replace(/\b[\wа-яА-Я]/g, function(l){
return l.toUpperCase();
});
var newCyrillicStr = strCyrillic.replace(/\b[\wа-яА-Я]/g, function(l){
return l.toUpperCase();
});
Here I got some CodePen example: http://codepen.io/brankoleone/pen/GNxjRM
You need a custom word boundary that you may build using groupings:
var strLatin = "this is some string";
var strCyrillic = "това е някакъв низ";
var block = "\\w\\u0400-\\u04FF";
var rx = new RegExp("([^" + block + "]|^)([" + block + "])", "g");
var newLatinStr = strLatin.replace(rx, function($0, $1, $2){
return $1+$2.toUpperCase();
});
console.log(newLatinStr);
var newCyrillicStr = strCyrillic.replace(rx, function($0, $1, $2){
return $1+$2.toUpperCase();
});
console.log(newCyrillicStr);
Details:
The block contains all ASCII letters, digits and underscore and all basic Cyrillic chars from the basic Cyrillic range (if you need more, see Cyrillic script in Unicode ranges Wiki article and update the regex accordingly), perhaps, you just want to match Russian with А-ЯЁёа-я, then use var block = "\\wА-ЯЁёа-я
The final regex matches and captures into Group 1 any char other than the one defined in the block or start of string, and then matches and captures into Group 2 any char defined in the block.
If you use Lodash, you can use _.startCase instead of your own implementation (they do it by splitting the string into words, capitalizing the 1st character of each word and then joining them back together)
Try it:
function capitalizer(string) {
return string.split(/\s/).map(function(item){
return (item.charAt(0).toUpperCase() + item.slice(1))
}).join(' ')
}
Example

User Profile Privacy screen with comma separated String

I have a listView with many fields and CheckBox next to each field. Screen similar to a FaceBook Profile screen with Privacy setting to each field. So friends can not see those fields if marked as Private.
On selection of CheckBox, i have to create a comma separated String.
Example,
FirstName Text ---> isFirstNamePrivate boolean
LastName Text ---> isLastNamePrivate boolean
...
I have to create a
String str = "FirstName,LastName"
if both are marked as Private.
If only isFirstNamePrivate is true then
String str = "FirstName"
Also if i receive a comma separated String from Service, with that i have to make those Boolean array.
Given::
String[] fieldNamesArray = "field1","field2","field3","field4","field5"};
Boolean[] isfieldPrivate = {true,false,true,false,true};
// fieldNamesArray.length will be equal to isfieldPrivate.length
Need to create below commaSeparatedStr from above given arrays.
//
String commaSeparatedStr = "field1,field3,field5";
Question is:
1) What is the optimized way to create a comma separated String.
2) What is the optimized way to create the Boolean array from the commaSeparatedString avoiding for loop on commaSeparatedStr .contains(str[n])
Given::
String[] fieldNamesArray = "field1","field2","field3","field4","field5"};
String commaSeparatedStr = "field1,field3,field5";
Need to create below Boolean array with commaSeparatedStr from above 2 arrays.
Boolean[] isfieldPrivate = {true,false,true,false,true};
// fieldNamesArray.length will be equal to isfieldPrivate.length
//
Where is the question part here?
If you are asking for a suggestion:
If there are 5 fields and first 3 are selected, make your string like
{1,1,1,0,0}
and pass it to your webservice. This would lighten the data package size.

VBA. Array for search or replace

Need to found any symbol of array.
For example:
replace(string,[a,b,c,e,f,g],"a1b2c3d4e567");
result = "1234567"
How do it ?
If your goal is to remove all non-numeric characters, the following will work:
' Added reference for Microsoft VBScript Regular Expressions 5.5
Const s As String = "a1b2c3d4e567"
Dim regex2 As New RegExp
Dim a As String
regex2.Global = True
regex2.Pattern = "[^0-9]"
Dim a As String = regex2.Replace(s, "")
MsgBox (a) ' Outputs 1234567
If you are looking for specific characters, change the pattern.
AFAIK you are going to have to do this by consecutive calls to replace
result = "a1b2c3d4e567"
result = replace(result,"a","")
result = replace(result,"b","")
result = replace(result,"c","")
etc

Resources