How to get substring from string in c#?

前端 未结 7 1553
夕颜
夕颜 2020-12-16 12:09

I have a large string and its stored in a string variable str. And i want to get a substring from that in c#? Suppose the string is : \" Retrieves a substring from thi

相关标签:
7条回答
  • 2020-12-16 12:30

    Riya,

    Making the assumption that you want to split on the full stop (.), then here's an approach that would capture all occurences:

    // add @ to the string to allow split over multiple lines 
    // (display purposes to save scroll bar appearing on SO question :))
    string strBig = @"Retrieves a substring from this instance. 
                The substring starts at a specified character position. great";
    
    // split the string on the fullstop, if it has a length>0
    // then, trim that string to remove any undesired spaces
    IEnumerable<string> subwords = strBig.Split('.')
        .Where(x => x.Length > 0).Select(x => x.Trim());
    
    // iterate around the new 'collection' to sanity check it
    foreach (var subword in subwords)
    {
        Console.WriteLine(subword);
    }
    

    enjoy...

    0 讨论(0)
  • 2020-12-16 12:35

    it's easy to rewrite this code in C#...

    This method works if your value it's between 2 substrings !

    for example:

    stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"
    

    calls should be:

    myNameValue = SplitStringByASubstring(stringContent , "[myName]")
    
    colorValue = SplitStringByASubstring(stringContent , "[color]")
    
    etcValue = SplitStringByASubstring(stringContent , "[etc]")
    
    0 讨论(0)
  • 2020-12-16 12:36

    Here is example of getting substring from 14 character to end of string. You can modify it to fit your needs

    string text = "Retrieves a substring from this instance. The substring starts at a specified character position.";
    //get substring where 14 is start index
    string substring = text.Substring(14);
    
    0 讨论(0)
  • 2020-12-16 12:42
    var data =" Retrieves a substring from this instance. The substring starts at a specified character position.";
    
    var result = data.Split(new[] {'.'}, 1)[0];
    

    Output:

    Retrieves a substring from this instance. The substring starts at a specified character position.

    0 讨论(0)
  • 2020-12-16 12:46
    string text = "Retrieves a substring from this instance. The substring starts at a specified character position. Some other text";
    
    string result = text.Substring(text.IndexOf('.') + 1,text.LastIndexOf('.')-text.IndexOf('.'))
    

    This will cut the part of string which lays between the special characters.

    0 讨论(0)
  • 2020-12-16 12:50

    You could do this manually or using IndexOf method.

    Manually:

    int index = 43;
    string piece = myString.Substring(index);
    

    Using IndexOf you can see where the fullstop is:

    int index = myString.IndexOf(".") + 1;
    string piece = myString.Substring(index);
    
    0 讨论(0)
提交回复
热议问题