C# 以第一个字符为例
我有一根绳子:大家好。我想从每个单词中提取前2个字符。结果是:Hetoal。我该怎么办?我试了试 字符串中的foreach字符串strC# 以第一个字符为例,c#,C#,我有一根绳子:大家好。我想从每个单词中提取前2个字符。结果是:Hetoal。我该怎么办?我试了试 字符串中的foreach字符串str 但是我收到了一个错误:无法将类型char转换为字符串您需要将句子字符串拆分为单词,如下所示: var sentence = "Hello to all."; var words = sentence.Split(' '); 然后,您可以循环遍历句子中的每个单词,获取每个单词的前两个字符,并将它们附加到结果中,如下所示: string result; var r
但是我收到了一个错误:无法将类型char转换为字符串您需要将句子字符串拆分为单词,如下所示:
var sentence = "Hello to all.";
var words = sentence.Split(' ');
然后,您可以循环遍历句子中的每个单词,获取每个单词的前两个字符,并将它们附加到结果中,如下所示:
string result;
var resultBuilder = new StringBuilder();
foreach(string word in words)
{
// Get the first two characters if word has two characters
if (word.Length >= 2)
{
resultBuilder.Append(word.Substring(0, 2));
}
else
{
// Append the whole word, because there are not two first characters to get
resultBuilder.Append(word);
}
}
result = resultBuilder.ToString();
代码示例:
string someString = "Hello to all";
string[] words = someString.Split(' ');
string finalString = "";
foreach (string word in words) {
finalString += word.Substring(0, 2);
}
// finalString = "Hetoal";
这会将字符串拆分为单词,然后在每个单词前找到前2个字符,并将它们附加到最后一个字符串对象。一种可能的解决方案是
string str = "Hello to all.";
StringBuilder output = new StringBuilder();
foreach (string s in str.Split(' '))
{
output.Append(s.Take(2));
}
string result = output.ToString();
你可以这样做
把你的绳子绕着空格分开
string[] words = s.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word.Substring(0,2));
}
这里有一些linq:
string s = "Hello to all";
var words = s.Split(' ');
var result = new string(words.SelectMany(w=>w.Take(2)).ToArray());
您的错误是因为当您枚举一个字符串时,您得到的是每个字符的字符,而不是字符串。所以它应该是字符串中的foreachchar c。但这可能不是您想要的。这假设字符串中有2个字符。你可以用Math.Min2,word.Length来代替2。请解释一下你的答案的技术细节。这会导致He。甚至不按照writeString结果需要初始值的方式编译;
String str = "Hello to all";
String[] words = str.Split(' ');
String completeWord = "";
foreach (String word in words)
{
if(word.Length>1)
completeWord+=word.Substring(0, 2);
}
string str = "Hello to all";
string result = str.Split().Select(word => word.Substring(0, 2)).Aggregate((aggr, next) => aggr + next);
//original message
string message = "hello to all";
//split into a string array using the space
var messageParts = message.Split(' ');
//The SelectMany here will select the first 2 characters of each
// array item. The String.Join will then concat them with an empty string ""
var result = String.Join("",messageParts.SelectMany(f=>f.Take(2)));
string word = "Hellow to all";
string result = "";
foreach(var item in word.Take(2))
{
result += item;
}
string myString = "Hello to all";
var result = myString
.Split(' ')
.Select(x => x.Substring(0,Math.Min(x.Length,2)))
.Aggregate((y,z) => y + z);