首页 > 解决方案 > 将单个字符串中的所有组合设为两位数

问题描述

我有一个这样的 Textbox1.Text:1784397425

我怎样才能从这里得到 2 个组合或 1 个组合?

这是一个模型:

喜欢17 78 84 43 39 97 74 42 25 1 7 8 4 3 9 7 4 2 5

那是另一个模型:

也可以是这样的:(第一个数字 1,我们取 1 乘 7,然后取 1 乘 8,依此类推。)

17 18 14 13 19 17 14 15 

等等...

78 74 73 79 77 74 72 75
84 83 89 87 84 82 85
43 49 47 44 42 45
39 37 34 32 35
and so on...

任何这样的模型算法都会对我有很大的帮助。

代码 3:不幸的是,这不能很好地工作。

Since they're strings to begin with you can use.
Left(str,n) n is the number of left characters you want.
Right(str,n) n is the number of Right characters you want.
Mid(str,n,nn) Mid is like substring where n is the starting char, and nn is the number from start you want from the str.

Dim line1 = "47"

Dim d1 As String = Left(line1,1)   'this is 4

Dim d2 As String = Right(line1,1)  'this is 7

now the math

Dim a1 As Integer = Int(d1) + Int(d2)

or 

Dim a1 As Integer = CInt(d1) + CInt(d2)

标签: vb.net

解决方案


正如 Andrew 所建议的,使用Substring提取您想要的字符串部分。

我已经将它包装在一个返回所有子字符串的迭代器中:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    TextBox2.Text = String.Join(" ", Substrings(TextBox1.Text, 2))
End Sub

Public Iterator Function Substrings(ByVal source As String, ByVal length As Integer) As IEnumerable(Of String)
    If length >= 1 AndAlso length <= source.Length Then
        For i As Integer = 0 To (source.Length - length)
            Yield source.Substring(i, length)
        Next
    End If
End Function

如果您希望用户设置长度参数的值,请在表单上放置一个NumericUpDown控件并.Value从中获取。


推荐阅读