Menu
  • HOME
  • TAGS

SCALA: change the separator in Array

Tag: arrays,string,scala,delimiter

I have an Array like this.

scala> var x=Array("a","x,y","b")
x: Array[String] = Array(a, x,y, b)

How do I change the separator comma in array to a :. And finally convert it to string like this.

String = "a:x,y:b"

My aim is to change the comma(separators only) to other separator(say,:), so that i can ignore the comma inside second element i.e, x,y. and later split the string using : as a delimiter

Best How To :

Your question is unclear, but I'll take a shot.

To go from:

val x = Array("a","x,y","b")

to

"a:x,y:b"

You can use mkString:

x.mkString(":")  

pointer to pointer dynamic array in C++

c++,arrays,pointers

The valid range of indices of an array with N elements is [0, N-1]. Thus instead of for example this loop for (int i=1; i <= n; i++) ^^^^ ^^^^^^ you have to write for ( int i = 0; i < n; i++ ) As you used operator new...

Blank screen on GridView

android,arrays,gridview

I executed ur code. Just add numberView.setTextColor(Color.BLACK); and it will work! :)...

REGEX python find previous string

python,regex,string

Updated: This will check for the existence of a sentence followed by special characters. It returns false if there are no special characters, and your original sentence is in capture group 1. Updated Regex101 Example r"(.*[\w])([^\w]+)" Alternatively (without a second capture group): Regex101 Example - no second capture group r"(.*[\w])(?:[^\w]+)"...

Translating a character array into a integer string in C++

c++,arrays,string

If you want a sequence of int, then use a vector<int>. Using the key_char string, the values of the chars in it will serve as the initial value of the ints. std::vector<int> key_num(key_char.begin(), key_char.end()); Then, iterate over each character of key_num and convert it to the equivalent int value for...

Create array from another with specific indices

javascript,arrays

You can use .map, like so var data = [ 'h', 'e', 'l', 'l', 'o', ' ' ]; var indices = [ 4, 0, 5, 0, 1, 2, 2 ]; var res = indices.map(function (el) { return data[el]; }); console.log(res); The map() method creates a new array with the results...

jQuery - Value in Function

jquery,arrays,function

You need to use brackets notation to access property by variable: function myFunc( array, fieldToCompare, valueToCompare ) { if( array[fieldToCompare] == "Thiago" ) alert(true); } And wrap name in quotes: myFunc( myArray, 'name', "Thiago" ); ...

Regex to remove `.` from a sub-string enclosed in square brackets

c#,.net,regex,string,replace

To remove all the dots present inside the square brackets. Regex.Replace(str, @"\.(?=[^\[\]]*\])", ""); DEMO To remove dot or ?. Regex.Replace(str, @"[.?](?=[^\[\]]*\])", ""); ...

Javascript: Labeling array results

javascript,arrays

Change you show function to this function show() { var content="<b>Your Plans For the Day:</b><br>"; for(var i = 0; i < Name.length; i++) { content += "Name " + Name[i]+"<br>"; } for(var i = 0; i < Date.length; i++) { content += "Date" + Date[i]+"<br>"; } for(var i = 0;...

What is the usage of adding an empty string in a javascript statement

javascript,string,concatenation

Type Casting. It converts the type to string If variable current.condition_field is not of string type, by adding '' at the end of it converts it to string. var field = current.condition_field + ''; So, field is always string. Thanks to @KJPrice: This is especially useful when you want to...

Notice: Array to string conversion in “path of php file” on line 64

php,mysql,arrays,oracle

Curly brackets are your friend when inserting variables into double quoted strings: $main_query=oci_parse($connection,"INSERT INTO ROTTAN(NAME,ROLLNO) VALUES('{$array[$rs][0]}','{$array[$rs][1]}')"); ...

.cpp:23: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’

c++,string

Use stoi, it's the modern C++ version of C's atoi. Update: Since the original answer text above the question was amended with the following error message: ‘stoi’ was not declared in this scope Assuming this error was produced by g++ (which uses that wording), this can have two different causes:...

do calculation inside JSONArray in Java

java,arrays,json

Here's what I would do. Replace <JSON STRING HERE> with the JSON String you were going to parse: ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>(); JSONArray arr = new JSONArray(<JSON STRING HERE>); for(int i = 0; i < arr.length(); i ++) { JSONObject obj = arr.getJSONObject(i); JSONArray valueArray = obj.getJSONArray("values"); ArrayList<Integer> dataList...

array and function php

php,arrays

$x and $y are only defined within the scope of the function. The code outside of the function does not know what $x or $y are and therefore will not print them. Simply declare them outside of the function as well, like so: <?php function sum($x, $y) { $z =...

Segmentation Fault if I don't say int i=0

c,arrays,segmentation-fault,initialization,int

In your code, int i is an automatic local variable. If not initialized explicitly, the value held by that variable in indeterministic. So, without explicit initialization, using (reading the value of ) i in any form, like array[i] invokes undefined behaviour, the side-effect being a segmentation fault. Isn't it automatically...

Regex pass dynamic values with boundry

c#,regex,string,boundary

Your first regular expression has a black slash followed by the letter b because of that @. The second one has the character that represents backspace. Just put an @ in front string bound = @"\b"; ...

A beginner questions about printf, java

java,string,printf

I'm sad that this question hasn't been answered, and upon that, I can't upvote it from it's -8 cause I don't have enough reputation. It seems downvoting is getting too unwarranted here. OP is just looking for an answer, which can be answered here and found online, he has tried...

Characters and Strings in Swift

ios,string,swift,unicode,character

When a type isn't specified, Swift will create a String instance out of a string literal when creating a variable or constant, no matter the length. Since Strings are so prevalent in Swift and Cocoa/Foundation methods, you should just use that unless you have a specific need for a Character—otherwise...

Substring of a file

javascript,arrays,substring

To get your desired output, this will do the trick: var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d"; var array = file.split(", ") // Break up the original string on `", "` .map(function(element, index){ var temp = element.split('|'); return [temp[0], temp[1], index + 1]; }); console.log(array); alert(JSON.stringify(array)); The split converts...

How do I print more than one value per key in Tcl?

arrays,tcl

You can't do it with arrays or dictionaries; both are mappings from keys to values. Instead, you need to use foreach with a key-value pair system directly: set pairs { set1 table set2 chair set1 chair } foreach {key value} $pairs { puts "$key is $value" } This does actually...

Comparing cell contents against string in Excel

string,excel,if-statement,comparison

We need an Array formula. In G2 enter: =NOT(ISERROR(MATCH(1,--EXACT(F$2:F$7,E2),0))) and copy down. Array formulas must be entered with Ctrl + Shift + Enter rather than just the Enter key. Note: The curly brackets that appear in the Formula Bar should not be typed....

Ruby: How to copy the multidimensional array in new array?

ruby-on-rails,arrays,ruby,multidimensional-array

dup does not create a deep copy, it copies only the outermost object. From that docs: Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. If you are not sure how deep your object...

How to innerHTML a function with array as parameter?

javascript,arrays,loops,foreach,innerhtml

Just take a variable for the occurrence of even or odd numbers. var myArray = function (nums) { var average = 0; var totalSum = 0; var hasEven = false; // flag if at least one value is even => true, otherwise false nums.forEach(function (value) { totalSum = totalSum +...

byte array to string and inverse : recoverded byte array is NOT match to original byte array in Java

java,string,bytearray

You cannot convert an arbitrary sequence of bytes to String and expect the reverse conversion to work. You will need to use an encoding like Base64 to preserve an arbitrary sequence of bytes. (This is available from several places -- built into Java 8, and also available from Guava and...

Memory consumption when chaining string methods

c#,string,immutability,method-chaining

Is it true that when you chain string functions, every function instantiates a new string? In general, yes. Every function that returns a modified string does so by creating a new string object that contains the full new string which is stored separately from the original string. There are...

Merge and sum values and put them in an array

javascript,arrays,angularjs,foreach

You cannot store key-value pair in array. Use object to store key-value pair. See comments inline in the code. var obj = {}; // Initialize the object angular.forEach(data, function(value, key) { if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) { if (obj[value.firstname]) { // If already exists obj[value.firstname] += value.distance;...

SCALA: change the separator in Array

arrays,string,scala,delimiter

Your question is unclear, but I'll take a shot. To go from: val x = Array("a","x,y","b") to "a:x,y:b" You can use mkString: x.mkString(":") ...

Comparing arrays with numbers in vb.net

arrays,vb.net

There are a few basic ways of checking for a value in an integer array. The first is to manually search by looping through each value in the array, which may be what you want if you need to do complicated comparisons. Second is the .Contains() method. It is simpler...

Android String if-statement

java,android,string

Correct me if I'm wrong. If you're saying that your code looks like this: new Thread(new Runnable() { public void run() { // thread code if (ready.equals("yes")) { // handler code } // more thread code }).start(); // later on... ready = "yes"; And you're asking why ready = "yes"...

Perl: Using Text::CSV to print AoH

arrays,perl,csv

Pretty fundamentally - CSV is an array based data structure - it's a vaguely enhanced version of join. But the thing you need for this job is print_hr from Text::CSV. First you need to set your header order: $csv->column_names (@names); # Set column names for getline_hr () Then you can...

Javascript function to validate contents of an array

javascript,arrays

You can use a simple array based test like var validCodes = ['IT00', 'O144', '6A1L', '4243', 'O3D5', '44SG', 'CE64', '54FS', '4422']; function validItems(items) { for (var i = 0; i < items.length; i++) { if (validCodes.indexOf(items[i]) == -1) { return items[i]; } } return ''; } var items = ["IT00",...

How to check if data already exists then randomly generate new data from an Array

php,mysql,arrays,mysqli

In my personal opinion, NEVER try to get data from an array within quotes! Always do it outside of quotes; especially in multi-denominational arrays. '$input[$rand_keys[$i]]' should be rewritten as '".$input[$rand_keys[$i]]."' OR '{$input[$rand_keys[$i]]}'. In my opinion it is better to do it outside of quotes instead of using { }. ...

Zipping two arrays together with index in Scala?

arrays,scala,zip

Simply do: array1.zip(array2).zipWithIndex.map { case ((a, b), i) => (a, b, i) } ...

Get elements containing text from array

javascript,jquery,html,arrays,contains

You can use :contains selector. I think you meant either one of those values, in that case var arr = ['bat', 'ball']; var selectors = arr.map(function(val) { return ':contains(' + val + ')' }); var $lis = $('ul li').filter(selectors.join()); $lis.css('color', 'red') <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li>...

Having two arrays in variable php

php,mysql,arrays,variables,multidimensional-array

The explode function is being used correctly, so your problem is further up. Either $data[$i] = mysql_result($result,$i,"data"); isn't returning the expected string "2015-06-04" from the database OR your function $data[$i] = data_eng_to_it_($data[$i]); isn't returning the expected string "04 June 2015" So test further up by echo / var_dump after both...

Infinite loop with fread

c,arrays,loops,malloc,fread

If you're "trying to allocate an array 64 bytes in size", you may consider uint8_t Buffer[64]; instead of uint8_t *Buffer[64]; (the latter is an array of 64 pointers to byte) After doing this, you will have no need in malloc as your structure with a 64 bytes array inside is...

Javascript sort array of objects in reverse chronological order

javascript,arrays,sorting

As PM 77-1 suggests, consider using the built–in Array.prototype.sort with Date objects. Presumably you want to sort them on one of start or end: jobs.sort(function(a, b) { return new Date(a.ys, a.ms-1) - new Date(b.ys, b.ms-1); }) ...

accessing range of values in arduino array

arrays,arduino

Arrays in C++ don't allow this syntax. What you should do is something like this: char[2] id; if( sx1272.packet_received.length > 5 ) { id[0] = sx1272.packet_received.data[4]; id[1] = sx1272.packet_received.data[5]; } ...

How to match words in 2 list against another string of words without sub-string matching in Python?

python,regex,string,loops,twitter

Store slangNames and riskNames as sets, split the strings and check if any of the words appear in both sets slangNames = set(["Vikes", "Demmies", "D", "MS", "Contin"]) riskNames = set(["enough", "pop", "final", "stress", "trade"]) d = {1: "Vikes is not enough for me", 2:"Demmies is okay", 3:"pop a D"} for...

most efficient way to create javascript array out of various php arrays

javascript,php,jquery,arrays

John, Try this: var dataSet = []; for (i = 0; i < mfrPartNumber.length; i++ ) { data = [dateReceived[i],name[i],color[i]]; dataSet.push(data); } This will build an array out of each instance of [i], and keep growing as your user keeps pushing the button....

C++11 Allocation Requirement on Strings

c++,string,c++11,memory,standards

Section 21.4.1.5 of the 2011 standard states: The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size(). The two...

C++ & Qt: Random string from an array area

c++,arrays,string,qt,random

You should use the random header. #include <random> std::default_random_engine generator; std::uniform_int_distribution dist(0, 5); int StringIndex = dist(generator); std::string ChosenString = characters[StringIndex]; The above will generate a random index into your array. If you want to limit the range, change the constructor of dist, for example (dist(0,2) would only allow for...

Remove quotes to use result as dataset name

r,string

You can get the values with get or mget (for multiple objects) lst <- mget(myvector) lapply(seq_along(lst), function(i) write.csv(lst[[i]], file=paste(myvector[i], '.csv', sep='')) ...

How to pass array in rails 4 strong parameters

ruby-on-rails,arrays

According to the docs https://github.com/rails/strong_parameters#permitted-scalar-values: The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile. To declare that the value in params must be an array of permitted scalar values map the key to an empty array: params.permit(:id => []) If...

How to pivot array into another array in Ruby

arrays,ruby,csv

Here is a way using an intermediate hash-of-hash The h ends up looking like this {"Alaska"=>{"Rain"=>"3", "Snow"=>"4"}, "Alabama"=>{"Snow"=>"2", "Hail"=>"1"}} myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] myFields = ["Snow","Rain","Hail"] h = Hash.new{|h, k| h[k] = {}} myArray.each{|i, j, k| h[i][j] = k } p [["State"] + myFields] + h.map{|k, v| [k] + v.values_at(*myFields)} output...

How can I convert an int to a string in C++11 without using to_string or stoi?

c++,string,c++11,gcc

Its not the fastest method but you can do this: #include <string> #include <sstream> #include <iostream> template<typename ValueType> std::string stringulate(ValueType v) { std::ostringstream oss; oss << v; return oss.str(); } int main() { std::cout << ("string value: " + stringulate(5.98)) << '\n'; } ...

How To Check Value Of String

javascript,css,string,numeric

document.GetElementById("tombolco").style = "display:block"; That's not the right way. This is document.getElementById("tombolco").style.display = 'block'; Also note that it is getElementById, not with a capital G. Same with 'none',Rest of your code is fine. Fiddle...

Array in Foreach (CodeIgniter)

php,arrays,codeigniter,foreach

You can use active record as below. $arrResult = $this->db ->where('id','foo') ->where_in('result',array(1,2)) // alternative to above condition //->where('(result = 1 OR result = 2)') ->get('mytable') ->result_array(); foreach($arrResult as $result){ // run code based on $result; } ...