|
Find the length of the string, then replace the search character with an empty string, then check the length again. The difference between the two lengths is the number of the characters in the original string. Doing it this way is usually much quicker than testing each character in turn, especially for longer strings.
=========================================================
I'm an optoholic - my glass is always half full of vodka.
=========================================================
|
|
|
|
|
Are you sure?
The replace function has to do the same iterating job internally. It will also create a new string instance when any replacement occurs. And you would have to use the Replace(String, String) method which is slower than operations on characters.
If speed cares I would use String.IndexOf(Char, Integer) within a while loop instead.
|
|
|
|
|
IndexOf is still going to have to compare every character, and has the added overhead of multiple method calls and argument validation.
Your original suggestion of iterating over the characters in the string would probably have the best performance (unless you start introducing unsafe code).
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Try it - you'll be surprised. Native functions and methods such as String.Replace are highly optimized and will be much faster than while loops and string comparisons.
=========================================================
I'm an optoholic - my glass is always half full of vodka.
=========================================================
|
|
|
|
|
I expected them to be highly optimised. My point was that Replace() is creating a new instance and operates on strings rather than characters (the Char version can't be used to remove characters).
IndexOf() is a native function too. On x86 machines the search can be performed with a single CPU instruction: scasw . So this will be faster than a normal loop comparing each character (which is still the expected answer for such homework assignments). If it is finally faster than using Replace() depends on the number of matches.
|
|
|
|
|
It will be highly dependent on the length of the strings. I had reason to write such a function a while back in tSQL for a database system and using the native Replace functionality was much more efficient than looping in all but the shortest of strings, but YMMV.
Module Module1
Sub Main()
Dim iCount As Integer
Dim strToSearch As String = "Every instance. Replace() will inteiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiirnally loop throughiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii the entire source string. It replaces all occurrences of the substring you want to replace. Tip: This behavior is useful when dealing with common string replacements in programs. But: If you do not understand this behavior you may end up writing inefficient code that has unneeded loops. "
Dim strSearchFor As String = "i"
Console.WriteLine(strToSearch)
iCount = strToSearch.Length() - strToSearch.Replace(strSearchFor, "").Length
Console.WriteLine("There are " + iCount.ToString() + " letter " + strSearchFor + "'s in the string")
End Sub
End Module
=========================================================
I'm an optoholic - my glass is always half full of vodka.
=========================================================
|
|
|
|
|
Using BenchmarkDotNet[^]:
public class StringCharCountBenchmark
{
private static readonly string _theStringToSearch = "Every instance. Replace() will inteiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiirnally loop throughiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii the entire source string. It replaces all occurrences of the substring you want to replace. Tip: This behavior is useful when dealing with common string replacements in programs. But: If you do not understand this behavior you may end up writing inefficient code that has unneeded loops. ";
private static readonly char _theCharToFind = 'i';
private static readonly string _theCharToFindAsString = "i";
[Benchmark]
public int UsingReplace()
{
return _theStringToSearch.Length - _theStringToSearch.Replace(_theCharToFindAsString, "").Length;
}
[Benchmark]
public int UsingForEachLoop()
{
int result = 0;
foreach (char c in _theStringToSearch)
{
if (c == _theCharToFind)
{
result++;
}
}
return result;
}
[Benchmark]
public int UsingForLoop()
{
int result = 0;
for (int i = 0; i < _theStringToSearch.Length; i++)
{
if (_theStringToSearch[i] == _theCharToFind)
{
result++;
}
}
return result;
}
} (Yes, I know: C#. But I'm sure you can convert to VB.NET if required. )
Results:
// * Summary *
BenchmarkDotNet=v0.11.1, OS=Windows 10.0.17134.228 (1803/April2018Update/Redstone4)
Intel Core i7-4770K CPU 3.50GHz (Haswell), 1 CPU, 8 logical and 4 physical cores
Frequency=3417969 Hz, Resolution=292.5714 ns, Timer=TSC
[Host] : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.3132.0
DefaultJob : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.3132.0
Method | Mean | Error | StdDev |
----------------- |-----------:|----------:|----------:|
UsingReplace | 3,923.6 ns | 15.267 ns | 12.749 ns |
UsingForEachLoop | 350.1 ns | 4.453 ns | 3.948 ns |
UsingForLoop | 376.1 ns | 7.239 ns | 8.046 ns |
Both loop options are fairly close. The String.Replace version takes roughly 10x as long.
The tool doesn't measure the memory usage, but it should be fairly self-evident that the Replace version will use more memory, since it has to allocate a new string each time.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Module Module1
Sub Main()
Dim strToSearch As String = "john????"
Dim strSearchFor As String = "?"
Console.WriteLine(strToSearch)
Console.WriteLine("There are " + CountOccurrences(strToSearch, strSearchFor).ToString() + " occurrences of " + strSearchFor + " in the string")
End Sub
Function CountOccurrences(strStringToSearch As String, strStringToCount As String) As Integer
Dim iCount As Integer
iCount = strStringToSearch.Length() - strStringToSearch.Replace(strStringToCount, "").Length
Return iCount
End Function
End Module
=========================================================
I'm an optoholic - my glass is always half full of vodka.
=========================================================
|
|
|
|
|
There is no alternative to filecopy that returns the percentage of files copied during the copy, since opening the file in binary mode is not necessary because the put and get commands are probably due to an overflow since I operate on 2GB files up.
|
|
|
|
|
There is no alternative built into VB6.
You're either going to have to code up your own version in something else that can be exposed to COM and handle 64-bit offsets, like in C#/VB.NET/C/C++, or just have the Shell copy files for you. In that case, you'll end up with the Explorer progress window, just as if you dragged and dropped a file to copy by hand.
|
|
|
|
|
And how do you make a copy with the shell, what command you have to run, and then shows the progress bar with the percentage of files copied?
|
|
|
|
|
|
Thanks a lot even though it was better if I did it with my PROGRess bar and with the instruct put and get opening it in binary....
|
|
|
|
|
You simply don't have that option in your own code because VB6 is 32-bit only and the largest integer it can handle is 2,147,483,647. That makes offsets into a file a max of 2.147GB.
|
|
|
|
|
I writ in italian(with percentage):
private Sub Form_Load()
'KPD-Team 2001
'URL: http://www.allapi.net/
'E-Mail: KPDTeam@Allapi.net
Dim Ret As Long
'set the graphics mode to persistent
Me.AutoRedraw = True
'print some text
Me.Print "Click the form to abort the filecopy"
'show the form
Me.Show
'start copying
Ret = CopyFileEx("c:\verybigfile.ext", "c:\copy.ext", AddressOf CopyProgressRoutine, ByVal 0&, bCancel, COPY_FILE_RESTARTABLE)
'show some text
Me.Print "Filecopy completed " + IIf(Ret = 0, "(ERROR/ABORTED)", "successfully")
End Sub
Private Sub Form_Click()
'cancel filecopy
bCancel = 1
End Sub
'in a module
Public Const PROGRESS_CANCEL = 1
Public Const PROGRESS_CONTINUE = 0
Public Const PROGRESS_QUIET = 3
Public Const PROGRESS_STOP = 2
Public Const COPY_FILE_FAIL_IF_EXISTS = &H1
Public Const COPY_FILE_RESTARTABLE = &H2
Public Declare Function CopyFileEx Lib "kernel32.dll" Alias "CopyFileExA" (ByVal lpExistingFileName As String, ByVal lpNewFileName As String, ByVal lpProgressRoutine As Long, lpData As Any, ByRef pbCancel As Long, ByVal dwCopyFlags As Long) As Long
Public bCancel As Long
Public Function CopyProgressRoutine(ByVal TotalFileSize As Currency, ByVal TotalBytesTransferred As Currency, ByVal StreamSize As Currency, ByVal StreamBytesTransferred As Currency, ByVal dwStreamNumber As Long, ByVal dwCallbackReason As Long, ByVal hSourceFile As Long, ByVal hDestinationFile As Long, ByVal lpData As Long) As Long
'adjust the caption
Form1.Caption = CStr(Int((TotalBytesTransferred * 10000) / (TotalFileSize * 10000) * 100)) + "% complete..."
'allow user input
DoEvents
'continue filecopy
CopyProgressRoutine = PROGRESS_CONTINUE
End Function
Trovato qui(restituisce pure la percentuale) https://www.experts-exchange.com/questions/20743248/Problem-Writing-Reading-a-File-2GB-HELP.html
testato con 10 gb di piu' fatelo voi ma dovrebbe funzionare,mi fido!!!!
|
|
|
|
|
Dear All,
Please help me in providing this solution.
I have just learned Microsoft Visual Basic. Net 2015 with SQL Server 2014.
One problem in update command method, I have prepared the program like this :
Dim i As Integer
Dim update1 As String = ("update datamahasiswa set no= ’" & TextBox1.Text & "’ where nama= ’" & TextBox2.Text & "’")
Try
Me.Validate()
Me.LatihanDataSetBindingSource.EndEdit()
Me.LatihanDataSet.Tables(0).Rows(1).Item(1) = TextBox1.Text
i = DatamahasiswaTableAdapter1.Update(LatihanDataSet.datamahasiswa)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
MessageBox.Show("no of rows updated=" & i)
The message shown up, like this :
update requires a valid update command when passed data row collection with modified rows. It means : the update method does not run well.
When I insert the command Executequery, this is not enlisted in VB.net
Please help me,
Thank you for your time and attention,
My best regards,
Muljanto
modified 6-Aug-18 7:45am.
|
|
|
|
|
Don't use string concatenation to generate SQL commands. Apart from leaving you wide open to SQL Injection Attacks[^], you can introduce other errors.
Use Parameterized queries instead: see Query Parameterization Cheat Sheet - OWASP[^]
So you would have some code like this
Dim update1 As String = ("update datamahasiswa set no= @parm1 where nama=@parm2") and then some code to add the parameters.
Note I have not included the single quotes ( ' ) in the sql to surround the variable name. You have actually used a ’ character - which is not the same as ' . Using parameterised queries removes errors like that.
|
|
|
|
|
You have not connected your update1 string to your table adapter. So your call to DatamahasiswaTableAdapter1.Update has nothing to work from.
|
|
|
|
|
Dear Mr Richard,
Please tell me how to connect the update command method with update1.
Dim i As Integer
Dim update1 As String = (“update datamahasiswa set no= & TextBox1.Text & where nama= &
TextBox2.Text & ”)
Try
Me.Validate()
Me.LatihanDataSetBindingSource.EndEdit()
Me.LatihanDataSet.Tables(0).Rows(1).Item(1) = TextBox1.Text
i = DatamahasiswaTableAdapter1.Update(LatihanDataSet.datamahasiswa)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
MessageBox.Show("no of rows updated=" & i)
The message : this needs valid update command
I propose this question, because it has not yet solved my problem.
Thank you for your time and attention,
My best regards,
Muljanto
|
|
|
|
|
|
Member 12813074 wrote: (“update datamahasiswa set no= & TextBox1.Text & where nama= & TextBox2.Text & ”)
You also seem to be failing String Handling 101.
That code will NOT put the value in TextBox1 into the string. Your actual SQL query will read like this every single time you execute it no matter what you type into the TextBoxes:
"update datamahasiswa set no= & TextBox1.Text & where nama= & TextBox2.Text & "
Again, it will NOT place the values of TextBox1.Text and TextBox2.Text into the SQL string you're building.
You might want to read up on this & Operator (Visual Basic) | Microsoft Docs[^].
Also, NEVER build SQL strings like this. You are blindly trusting user input. That is a bad thing. You're opening yourself up to destroying your database, either accidentally or maliciously. Google for "SQL Injection Attack" to find out why what you're doing is so bad.
|
|
|
|
|
Dear All,
I have revised this code based on my update information, but the record has not yet updated.
Please help me in adding and updating a data table.
My code is below, like that
Dim i As Integer
Dim latihandataset As New latihanDataSet()
Dim datamahasiswatableadapter As New latihanDataSetTableAdapters.datamahasiswa1TableAdapter
Try
Me.Validate()
Me.LatihanDataSetBindingSource.EndEdit()
Me.LatihanDataSet.Tables(0).Rows(1).Item(1) = TextBox1.Text
i = DatamahasiswaTableAdapter1.Update(Me.LatihanDataSet.datamahasiswa)
Me.DatamahasiswaTableAdapter1.Update(Me.LatihanDataSet.datamahasiswa)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
MessageBox.Show("no of rows updated=" & i)
The result : It have no a bug error, but the updated program have not run well.
Please help me to create the valid code for update a data.
Thank you for you time and attention,
My best regards,
Muljanto
modified 8-Aug-18 5:21am.
|
|
|
|
|
Dear Mr Dave,
I have done the some feedback.
- by restructuring the table adapter
- by putting the primary key
The result : It is no error bug, but the record has not yet updated succesfully.
The code :
Dim i As Integer
Dim latihandataset As New latihanDataSet()
Dim datamahasiswatableadapter As New latihanDataSetTableAdapters.datamahasiswa1TableAdapter
Try
Me.Validate()
Me.LatihanDataSetBindingSource.EndEdit()
Me.LatihanDataSet.Tables(0).Rows(1).Item(1) = TextBox1.Text
i = DatamahasiswaTableAdapter1.Update(latihandataset.datamahasiswa)
Me.DatamahasiswaTableAdapter1.Update(latihandataset.datamahasiswa)
Me.DatamahasiswaTableAdapter1.Fill(latihandataset.datamahasiswa)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
MessageBox.Show("no of rows updated=" & i)
Please help me to rectify this code.
Thank so much for your time and attention,
My best regards,
Muljanto
|
|
|
|
|
Dear All,
I have revised this code, and putted the primary key on one field in DatamahasiswaTableAdapter1.
It does not run well.
Please help me in obtaining a solution about creating a code for adding and updating a data table.
My code is below, like that
Dim i As Integer
Dim update1 As DataTable = Me.DataGridView1.DataSource
Try
Me.Validate()
Me.LatihanDataSetBindingSource.EndEdit()
Me.LatihanDataSet.Tables(0).Rows(1).Item(1) = TextBox1.Text
i = DatamahasiswaTableAdapter1.Update(LatihanDataSet.datamahasiswa)
Me.DatamahasiswaTableAdapter1.Update(update1)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
MessageBox.Show("no of rows updated=" & i)
The result : This happened the same bug error, like the previous one
Please help me to create the valid code for update a data.
Thank you for you time and attention,
My best regards,
Muljanto
|
|
|
|
|