字符串修剪从后面到特定的三个字符

时间:2016-01-18 08:41:56

标签: vb.net string substring reverse

如何修剪一些字符串,直到我得到三个特定字符,例如" xyz"。确切地说,我将举一个例子:

Dim String1 as String = "GunsAndRosesWelcomeToTheJungle" 
Dim String2 as String = "DontCry"
Dim ResultString as String

我需要删除所有内容,直到"moc" (reverse "com")String1string2并添加ResultString以获取"GunsAndRosesWelDontCry"

ResultString应为:<select id="filter"> <option value="" disabled selected>Select Body Part</option> <option value="Chest">Chest</option> <option value="Back">Back</option> </select> <tr> <th>#</th> <th>Exercise name</th> <th>Target Muscle</th> </tr> @foreach ($exercises as $exercise) <tr class="{{$exercise->bodyPart}} bodyparts"> <td>{{$exercise->id}}</td> <td>{{$exercise->name}}</td> <td>{{$exercise->bodyPart}}</td> </tr> @endforeach <script language="javascript"> $(document).ready(function(e) { $("#filter").change(function(){ if($(this).val() != ""){ $(".bodyparts").hide(); $("." + $(this).val()).show(); } }); }); </script>

2 个答案:

答案 0 :(得分:2)

您可以使用String.IndexOfString.Substring并从前面开始解决问题:

Dim String1 as String = "GunsAndRosesWelcomeToTheJungle" 
Dim String2 as String = "DontCry"
Dim index = String1.IndexOf("com")
Dim ResultString as String = String1.Substring(0, index) + String2

编辑:

如果由于某种原因需要反转子串输入和字符串,我会引入一个像这样的反向字符串函数

Private Function Reverse(Val As String) As String
    Dim charArray As Char() = Val.ToCharArray()
    Array.Reverse(charArray)
    Return New String(charArray)
End Function

然后像这样使用它

Dim String1 As String = "GunsAndRosesWelcomeToTheJungle"
Dim String2 As String = "DontCry"        
Dim index = String1.Length - Reverse(String1).IndexOf(Reverse("com")) - ("com").Length
Dim ResultString As String = String1.Substring(0, index) + String2

否则,我们可以使用String.LastIndexOf

Dim String1 as String = "GunsAndRosesWelcomeToTheJungle" 
Dim String2 as String = "DontCry"
Dim index = String1.LastIndexOf("com")
Dim ResultString as String = String1.Substring(0, index) + String2

答案 1 :(得分:0)

你可以这样试试,

Dim String1 As String = "GunsAndRosesWelcomeTocomeThecomJunglecom"
Dim String2 As String = "DontCry"
Dim ResultString As String
Dim ar As String() = String1.Split("com")
ResultString = ar(0) & String2

Demo