2017-05-29 85 views
-1

我正在開發函數,它會給我特定字符串的右側。函數有可能根據splitted char返回字符串,將char保留在字符串中,而且最重要的是要麼返回字符串將在該char分隔符的最後一次出現之後或者說在字符串中的分隔符occerence的哪個位置之後,返回字符串後採取。任何人都可以看看,並確認是否正確的方式去或該代碼是否包含任何問題?按特定要求取字符串的特定字符串部分

請記住使用lastindex我將lastindexof設置爲true,並且當splitterCharPosition必須設置時,splitterCharPosition是什麼,反之亦然。

這是我當前的代碼,以確認:

Public Function GetRightSideStringByCHar(splitterChar As String, searchingWord As String, keepCharAsWell As Boolean, lastindexof As Boolean, splitterCharPosition As Integer) As String 
     Dim index As Integer 
     Select Case lastindexof 
      Case False 
       index = GetNthIndex(searchingWord, splitterChar, splitterCharPosition) 
      Case True 
       index = searchingWord.LastIndexOf(splitterChar) 
     End Select 

     If index > 0 Then 
      If keepCharAsWell Then 
       searchingWord = searchingWord.Substring(0, index + splitterChar.Length) 
      Else 
       searchingWord = searchingWord.Substring(0, index) 
      End If 
     Else 
      searchingWord = String.Empty 
     End If 
     Return searchingWord 
    End Function 

Helper功能,將得到n個指標:根據您的其他問題,刪除

Public Function GetNthIndex(searchingWord As String, charseparator As Char, n As Integer) As Integer 
     Dim count As Integer = 0 
     For i As Integer = 0 To searchingWord.Length - 1 
      If searchingWord(i) = charseparator Then 
       count += 1 
       If count = n Then 
        Return i 
       End If 
      End If 
     Next 
     Return -1 
    End Function 
+0

你究竟在問什麼?你是否運行這段代碼?它工作嗎?如果你要求審查,那麼你可以嘗試在https://codereview.stackexchange.com/上提出這個問題。 –

回答

0

,我制定了這個要求。

它適用於您以前的所有示例。

[parameters] 
str = input string 
strtofind = separator string 
occurance = zero-based index to start cutting (optional) 
keepstringtofind = append separator to string (optional) 
righttoleft = operational direction (optional) 

    Public Function CutFromString(str As String, strtofind As String, Optional occurance As Integer = 0, Optional keepstrtofind As Boolean = False, Optional righttoleft As Boolean = False) As String 
    Dim s As String = str 
    Dim sections As List(Of String) = IIf(String.IsNullOrEmpty(str), New List(Of String), str.Split(strtofind.ToCharArray).ToList) 
    If sections.Count = 1 AndAlso sections.First = str Then sections.Clear() 
    If occurance < sections.Count Then 
     Dim b = sections.Count - occurance 
     While b > 0 
      If righttoleft Then 
       sections.RemoveAt(0) 
      Else 
       sections.RemoveAt(sections.Count - 1) 
      End If 
      b -= 1 
     End While 
     s = Join(sections.ToArray, strtofind) 
     If keepstrtofind And occurance > 0 Then 
      If righttoleft Then 
       s = strtofind + s 
      Else 
       s += strtofind 
      End If 
     End If 
    End If 
    Return s 
End Function 
+0

似乎不適用於所有情況。對於這個例子:Console.WriteLine(CutFromString(「1 34.1t0#$ 1.trweL24w222」,「。」,1,True,True))仍然沒有點在開始我標記保持或這個例子:CutFromString(「14.1001.2 「,」。「,1,True,True)應該是:14.1001。我得到:2 – DinoDinn

+0

修復了一些錯誤,試試這個版本 – Mike