MiXs
(MxSvensson)
September 1, 2023, 5:50am
1
I would appreciate your help when it comes to finding duplicates in a string.
Imagine that I have an array that looks like this:
apple; apple; banana; orange; kiwi; apple
Then I want to find all duplicates and put, for example, a 1 in front of the first duplicate and then a 2 on the next one, etc.
Like this: apple1;apple2;banana;orange;kiwi;apple3
I have tried different loops but nothing has worked well, have also tried this which ppr has answered in a question.
But did not get it to work satisfactorily.
If anyone has a Lambda expression that would work, I would be extremely grateful.
Regards Mike
sarathi125
(Parthasarathi)
September 1, 2023, 6:02am
2
@MiXs ,
Welcome Back!
Try something similar to this, this is for a list, so you can try by converting your array into a list.
listx.[Select](Function(s, i) New With {Key
.orgstr = s, Key
.index = i
}).GroupBy(Function(x) x.orgstr).SelectMany(Function(g) g.[Select](Function(x, j) New With {Key
.item = x, Key
.suffix = j + 1, Key
.count = g.Count()
})).OrderBy(Function(x) x.item.index).[Select](Function(x) If(x.count = 1, x.item.orgstr, x.item.orgstr & "_" + x.suffix)).ToList()
Parvathy
(PS Parvathy)
September 1, 2023, 6:13am
3
Hi @MiXs
inputStr = "apple; apple; banana; orange; kiwi; apple"
words = inputStr.Split(";"c)
wordCounts As New Dictionary(Of String, Integer)
result As New List(Of String)
For Each word In words
Dim trimmedWord As String = word.Trim()
If Not wordCounts.ContainsKey(trimmedWord) Then
wordCounts(trimmedWord) = 1
result.Add(trimmedWord)
Else
wordCounts(trimmedWord) += 1
result.Add(trimmedWord & wordCounts(trimmedWord).ToString())
End If
Next
At the end of For Each you can print this using Log Message or Message Box
Dim finalStr As String = String.Join(“;”, result)
Hope it helps!
MiXs
(MxSvensson)
September 1, 2023, 7:06am
4
Thank you so much @sarathi125
I get that:
With Option Strict On, implicit conversions from String to Double are not allowed.
Where am I doing wrong?
Regards Mike
MiXs
(MxSvensson)
September 1, 2023, 7:35am
6
I think i solved it, i added a .ToString to this part:
item.orgstr & “_” + x.suffix.ToString)).ToList()
1 Like
MiXs
(MxSvensson)
September 1, 2023, 7:42am
7
Thank you so much @sarathi125 it worked perfectly
@Parvathy thanks so much for your input, really appreciated!
Regards Mike
system
(system)
Closed
September 4, 2023, 7:43am
8
This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.