【发布时间】:2018-05-16 19:50:40
【问题描述】:
我正在尝试在 c# 中拆分字符串。我收到一个带有多个空格的字符串,我想在空格处拆分它。到目前为止,我所尝试的一切都失败了。它不会引发错误,只是将字符串保持为空
using System;
using System.Diagnostics;
using System.Management;
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId);
public static Process GetActiveWindowProcess(){
var processWithFocus = GetForegroundWindow();
int processId;
GetWindowThreadProcessId(processWithFocus, out processId);
Process process = Process.GetProcessById(processId);
return process;
}
public static String getCommandLine(){
string wmiQueryString = "SELECT * FROM Win32_Process WHERE ProcessId = " + process.Id;
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
{
using (var results = searcher.Get())
{
ManagementObject mo = results.Cast<ManagementObject>().FirstOrDefault();
if (mo != null)
{
String str = (string)mo["CommandLine"];
Debug.WriteLine(str.Split(' ')); //Splitting the string
return str;
}
}
}
}
我尝试了所有我能找到的方法,但结果都是一样的。字符串在那里,但字符串数组为空。
var ssizes = myStr.Split(" \t".ToCharArray());
string[] ssize = myStr.Split(null);
string[] ssize = myStr.Split(new char[0]);
//all arrays are emtpy...
我错过了什么吗?
编辑 抱歉,错误出现在我的网站上。调试不输出数组。我误以为它是空的。
【问题讨论】:
-
String.Split有效。它每天被使用数百万次。发布演示问题的相关代码,并附上示例。众所周知,您的字符串可能不包含您认为的分隔符 -
(string)mo["CommandLine"];中的值是什么,请提供给我们 -
Debug.WriteLine()应该显示System.String[]。请点击minimal reproducible example。您可以在不提及 WMI 或 Process 的情况下重写此问题。 -
上面的代码工作正常,你只是在这里输出了错误的东西。
-
Split永远不会返回空数组,即使提供的字符串中不存在分隔符,结果也会包含单个项目,即参数本身。
标签: c# string windows visual-studio-2017