Is there an equivalent to 'sscanf()' in .NET?

后端 未结 8 1599
故里飘歌
故里飘歌 2020-12-10 11:46

The .NET Framework gives us the Format method:

string s = string.Format(\"This {0} very {1}.\", \"is\", \"funny\");
// s is now: \"This is very funny.\"
         


        
8条回答
  •  感动是毒
    2020-12-10 12:14

    I came across the same problem, i belive that there is a elegante solution using REGEX... but a came up with function in C# to "UnFormat" that works quite well. Sorry about the lack of comments.

        /// 
        /// Unformats a string using the original formating string. 
        /// 
        /// Tested Situations:
        ///    UnFormat("1", "{0}") : "1"
        ///    UnFormat("2", "{0}") : "2"
        ///    UnFormat("3
    ", "{0}
    ") : "3" /// UnFormat("
    4", "
    {0}") : "4" /// UnFormat("5", "") : "5" /// UnFormat("
    6", "{0}") : "6" /// UnFormat("2009-10-02", "{0:yyyy-MM-dd}") : "2009-10-02" /// UnFormat("", "{0}") : "" /// UnFormat("bla", "{0}") : "bla" ///
    /// /// /// If an "unformat" is not possible the original string is returned. private Dictionary UnFormat(string original, string formatString) { Dictionary returnList = new Dictionary(); try{ int index = -1; // Decomposes Format String List formatDecomposed = new List (formatString.Split('{')); for(int i = formatDecomposed.Count - 1; i >= 0; i--) { index = formatDecomposed[i].IndexOf('}') + 1; if (index > 0 && (formatDecomposed[i].Length - index) > 0) { formatDecomposed.Insert(i + 1, formatDecomposed[i].Substring(index, formatDecomposed[i].Length - index)); formatDecomposed[i] = formatDecomposed[i].Substring(0, index); } else //Finished break; } // Finds and indexes format parameters index = 0; for (int i = 0; i < formatDecomposed.Count; i++) { if (formatDecomposed[i].IndexOf('}') < 0) { index += formatDecomposed[i].Length; } else { // Parameter Index int parameterIndex; if (formatDecomposed[i].IndexOf(':')< 0) parameterIndex = Convert.ToInt16(formatDecomposed[i].Substring(0, formatDecomposed[i].IndexOf('}'))); else parameterIndex = Convert.ToInt16(formatDecomposed[i].Substring(0, formatDecomposed[i].IndexOf(':'))); // Parameter Value if (returnList.ContainsKey(parameterIndex) == false) { string parameterValue; if (formatDecomposed.Count > i + 1) if (original.Length > index) parameterValue = original.Substring(index, original.IndexOf(formatDecomposed[i + 1], index) - index); else // Original String not valid break; else parameterValue = original.Substring(index, original.Length - index); returnList.Add(parameterIndex, parameterValue); index += parameterValue.Length; } else index += returnList[parameterIndex].Length; } } // Fail Safe #1 if (returnList.Count == 0) returnList.Add(0, original); } catch { // Fail Safe #2 returnList = new Dictionary(); returnList.Add(0, original); } return returnList; }

提交回复
热议问题