我目前正在尝试将用户选择的字符串关键字拆分为每个字母。但是,我无法说要在特定字母后进行拆分,因为在程序运行之前,我无法知道它将是哪个单词。我希望每个单独的字母都以某种方式分开存储,以便以后可以参考。
到目前为止,我已经尝试使用.Split方法执行此操作,并且如我的代码所示,没有运气。
int keyLength = txtKeyword.Text.Length; // Calculate length of keyword
string KeyCount = txtKeyword.Text; // Count the characters
string[] Count3 = KeyCount.Split(char, StringSplitOptions.None);
string[] keywordArray = new string[keyLength];
for (int i = 0; i < keyLength ; i++)
{
keywordArray[i] = Count3[i];
listBox1.Items.Add(keywordArray[i]);
}
我在说“ char”的括号中出现错误,不确定为什么。
答案 0 :(得分:1)
我建议使用:
char[] charArray = KeyCount.ToCharArray();
但是您的数据类型将是char[]
,而不是string[]
如果您确实需要字符串,可以这样做:
string[] stringArray = charArray.Select(c => c.ToString()).ToArray();
答案 1 :(得分:0)
我希望我能很好地理解您的问题,但是对我来说这似乎太容易了,因为我根本没有使用split:
char[] splittedText;
string test = "narmin";
private void Window_Loaded(object sender, RoutedEventArgs e)
{
splittedText = new char[test.Length];
for (int i =0 ; i<test.Length;i++)
{
splittedText[i] = test[i];
}
}
答案 2 :(得分:0)
您收到一个错误,因为它期望一个select 'On-Site Case Rate' Exp1,
CONCAT(isnull(sum(onsite.a) * 100 / count(onsite.casecount), 0), '%') '400',
CONCAT(isnull(sum(onsite.b) * 100 / count(onsite.casecount), 0), '%') '401'
from onsite
,而不是类型char
。
以下是char
方法的示例用法。
Split
如Compufreak所指出的,您可以使用string KeyCount = "1.2.3.4.5";
string[] Count3 = KeyCount.Split('.');
// Count3 would be ["1","2","3","4","5"] now
// Note how the "." were cut during the Split operation
将string
变成char[]
。
这是使用原始ToCharArray()
的各个字符的更深入的方法:
string
关于创建数组后如何访问字符的几种方法:
// Get the length of the Keyword (amount of characters in the string)
int keyLength = txtKeyword.Text.Length;
// Store the Text of the TextBox in a variable
string keywordString = txtKeyword.Text;
// Turn the string into an array of chars
char[] charArray = keywordString.ToCharArray();
// Turn the array of chars into an array of strings
string[] stringArray = charArray.Select(c => c.ToString()).ToArray();
但是,由于您可以像遍历// 1. Iterate through the array with a foreach loop
foreach (char character in charArray)
{
// Do stuff with the character
char tempChar = character;
if (character == 'a')
{
// Do stuff
}
}
// 2. Iterate through the array with a for loop
for (int i = 0; i < charArray.Length; i++)
{
char tempChar = charArray[i];
}
// 3. Get the character at a specific position (read: index) in the array
char tempChat = charArray[0];
// The string array works exactly the same for all three methods
foreach (string singleString in stringArray)
{
// Do stuff with the string
string tempString = singleString;
if (tempString == "a")
{
// Do stuff
}
}
一样遍历char数组,因此可以执行以下操作。请注意,我是如何使用string
而不是新数组的。
keywordString