Skip to content

Instantly share code, notes, and snippets.

@icywind
Last active August 25, 2023 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icywind/961b41fcbdf9af6fcfb52dcf4845f6fd to your computer and use it in GitHub Desktop.
Save icywind/961b41fcbdf9af6fcfb52dcf4845f6fd to your computer and use it in GitHub Desktop.
C# to read python format string
// input: [1,2]
public static int[] ParseOneDimArray(string str)
{
string text = str.Substring(1, str.Length-2);
int [] arrayint = text.Split(',').Select(x=> int.Parse(x)).ToArray();
return arrayint;
}
// input: [[1,2],[3,4]]
public static int[][] ParseTwoDimArray(string str)
{
List<int[]> list = new List<int[]>();
var regex = new Regex(@"\[(\-*\d*)(,\-*\d+)*\]",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
string text = str.Substring(1, str.Length-2);
MatchCollection matches = regex.Matches(text);
// Report on each match.
foreach (Match match in matches)
{
GroupCollection groups = match.Groups;
//Console.WriteLine("match:{0}", match.Value);
foreach(Group group in groups)
{
// Console.WriteLine("group {0}:{1}", group.Index, group.Value);
}
string arraystr = match.Value;
text = arraystr.Substring(1, arraystr.Length-2);
int [] arrayint = text.Split(',').Select(x=> int.Parse(x)).ToArray();
list.Add(arrayint);
}
return list.ToArray();
}
public static string Array1ToString(int [] array)
{
string str = "[" + string.Join(',', array) + "]";
return str;
}
public static string Array2ToString(int[][] array)
{
string [] ss = array.Select(x=> "[" + string.Join(',', x) + "]").ToArray();
string str = "[" + string.Join(',', ss) + "]";
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment