Menu
  • HOME
  • TAGS

Return index of word in string

Tag: arrays,vb.net,vbscript

This code:

Module Module1
    Sub Main()
    ' Our input string.
    Dim animals As String = "cat, dog, bird"

    ' See if dog is contained in the string.
    If Not animals.IndexOf("dog") = -1 Then
        Console.WriteLine(animals.IndexOf("dog"))
    End If
    End Sub
End Module

Return start position 5 in string

But how to return index of string so:

for cat = 1
for dog = 2
for bird = 3

Best How To :

Looking at your desired output it seems you want to get the index of word in your string. You can do this by splitting the string to array and then finding the item in an array using method Array.FindIndex:

Dim animals = "cat, dog, bird"

' Split string to array
Dim animalsArray = animals.Split(New String() {",", " "}, StringSplitOptions.RemoveEmptyEntries)

' Item to find
Dim itemToFind = "dog"
' Find index in array
Dim index = Array.FindIndex(Of String)(animalsArray, Function(s) s = itemToFind)
' Add 1 to the output:
Console.WriteLine(index + 1)

Above code returns 2. For cat you would get 1 and for bird the result would be 3. If there is no item in the array the output would be 0

How to pass all value of ListBox Control to a function?

vb.net,listbox

You're passing the contents of a ListBox to a method that is just displaying them in a MsgBox(). There are two approaches you can do to accomplish what I think you're wanting. You can pass ListBox.Items to the method and iterate through each item concatenating them into a single String...

Split an array into slices, with groupings

arrays,ruby,enumerable

Yes, this bookkeeping with i is usually a sign there should be something better. I came up with: ar =[ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york" }, { name: "bar1", location: "new york" }, { name:...

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

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

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

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

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

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

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

Removing Alert When Using DeleteFile API

vb.net,vba,api,delete

There are several SHFILEOPSTRUCT.fFlags options you'll want to consider. You are asking for FOF_NOCONFIRMATION, &H10. You probably want some more, like FOF_ALLOWUNDO, FOF_SILENT, FOF_NOERRORUI, it isn't clear from the question. Check the docs.

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

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

Convert date to string format

vb.net,converter

Your approach doesn't work because you are using ToString on a DataColumn which has no such overload like DateTime. That doesn't work anyway. The only way with the DataTable was if you'd add another string-column with the appropriate format in each row. You should instead use the DataGridViewColumn's DefaultCellStyle: InvestorGridView.Columns(1).DefaultCellStyle.Format...

Array JLabel ActionListener multiple JPanels

java,arrays,swing

You cannot directly add an ActionListener to a JLabel - it doesn't have that functionality. Instead, you should create a MouseAdapter, override the mouseClicked method, and use JLabel.addMouseListener to add it to your JLabels. The best way to get it to, as you say, "display a panel and the other...

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(":") ...

ZipEntry() and converting persian filenames

vb.net,persian,sharpziplib

Try setting IsUnicodeText to true: 'VB.NET Dim newEntry = New ZipEntry(entryName) With { _ Key .DateTime = DateTime.Now, _ Key .Size = size, _ Key .IsUnicodeText = True _ } //C# var newEntry = new ZipEntry(entryName) { DateTime = DateTime.Now, Size = size, IsUnicodeText = true }; ...

Select word between two words

javascript,arrays,jquery-selectors

Here's a quick split and reduce: var arr = str.split("By ").reduce(function(acc, curr) { curr && acc.push(curr.split(" ")[0]); return acc; }, []); Result: ["Greili", "ToneBob", "hela222", "NovaSplitz"] Demo: JSFiddle...

Convert Double from String

asp.net,vb.net,visual-studio-2012,converter

The result isn't wrong, it only has lower precision than you expected. Floating point numbers have a limited precision by design, and you simply can't expect to get a result that is more precise than its limit. You can use a Decimal to get higher precision. In this case it...

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

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

Custom drawing using System.Windows.Forms.BorderStyle?

c#,.net,vb.net,winforms,custom-controls

If you want to get results that reliably look like the BorderStyles on the machine you should make use of the methods of the ControlPaint object. For testing let's do it ouside of a Paint event: Panel somePanel = panel1; using (Graphics G = somePanel.CreateGraphics()) { G.FillRectangle(SystemBrushes.Window, new Rectangle(11, 11,...

NullReference Error while assiging values of Modeltype in MVC View (Razor)

vb.net,razor,model-view-controller,model

You need to pass the model instance to the view: Function Details() As ActionResult Dim employee As Employee employee = New Employee employee.EmployeeID = 101 Return View(employee) End Function ...

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

Can't output Guid Hashcode

sql,vb.net,guid,hashcode

Well, are you looking for a hashcode like this? "OZVV5TpP4U6wJthaCORZEQ" Then this answer might be useful: Guid g = Guid.NewGuid(); string GuidString = Convert.ToBase64String(g.ToByteArray()); GuidString = GuidString.Replace("=",""); GuidString = GuidString.Replace("+",""); Extracted from here. On the linked post there are many other useful answers. Please take a look! Other useful links:...

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

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

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 XML node value when previous node value conditions are true (without looping)

xml,vb.net,linq-to-xml

UPDATE Using an XDocument vs an XmlDocument, I believe this does what you're asking without using loops. This is dependent on the elements being in the order of <PhoneType> <PhonePrimaryYN> <PhoneNumber> string xml = "<?xml version=\"1.0\"?>" + "<Root>" + " <PhoneType dataType=\"string\">" + " <Value>CELL</Value>" + " </PhoneType>" + "...

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

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

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

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

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

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

Retrieve full path of FTP file on drag & drop?

vb.net,ftp

If the data dropped contains a UniformResourceLocator format, you can get the entire URL from that, for example: Private Sub Form1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop If e.Data.GetDataPresent("UniformResourceLocator") Then Dim URL As String = New IO.StreamReader(CType(e.Data.GetData("UniformResourceLocator"), IO.MemoryStream)).ReadToEnd End If End Sub It first checks to see if a...

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

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

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

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

Visual Basic Datagrid View change row colour

vb.net,datagridview,datagrid

Is it possible that your datagridview isn't loaded fully when you try to recolor the rows? Since you are setting the datasource, you should put your code that affects the grid after you can make sure that it is finished loading. The column widths change because it is not dependent...

Blank screen on GridView

android,arrays,gridview

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

how to modify an array value with given index?

arrays,linux,bash

You don't need the quotes. Just use ${i}, or even $i: pomme[${i}]="" Or pomme[$i]="" ...

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]}')"); ...

Gridview items not populating correctly

asp.net,vb.net

Try this vb code behind, then comment out my test Private Sub BindGrid() Dim dt_SQL_Results As New DataTable '' Commenting out to use test data as I have no access to your database 'Dim da As SqlClient.SqlDataAdapter 'Dim strSQL2 As String 'Dim Response As String = "" 'strSQL2 = "SELECT...

Java, cut off array line before charactern nr. X

java,arrays,string,break

Assuming it is an String array, below code should do for (int i = 0; i < stringArrAC.length; i++) { stringArrAC[i] = stringArrAC[i].substring(64); } ...

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

Connecting to database using Windows Athentication

sql-server,vb.net,authentication,connection-string

You need to add Integrated Security=SSPI and remove username and password from the connection string. Dim ConnectionString As String = "Data Source=Server;Initial Catalog=m2mdata02;Integrated Security=SSPI;" ...