我有这个字符串: Hello to all 。
我想从每个单词中取出前2个字符。结果:Hetoal。我能怎么做?我试过一个foreach
foreach(字符串str in String)
但我收到错误:无法将char类型转换为String
答案 0 :(得分:3)
您需要将句子字符串拆分为单词,如下所示:
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();
答案 1 :(得分:1)
代码示例:
string someString = "Hello to all";
string[] words = someString.Split(' ');
string finalString = "";
foreach (string word in words) {
finalString += word.Substring(0, 2);
}
// finalString = "Hetoal";
这会将字符串拆分为单词,然后在foreach单词中找到前2个字符并将它们附加到finalString
对象。
答案 2 :(得分:1)
一种可能的解决方案是
string str = "Hello to all.";
StringBuilder output = new StringBuilder();
foreach (string s in str.Split(' '))
{
output.Append(s.Take(2));
}
string result = output.ToString();
答案 3 :(得分:1)
string myString = "Hello to all";
var result = myString
.Split(' ')
.Select(x => x.Substring(0,Math.Min(x.Length,2)))
.Aggregate((y,z) => y + z);
答案 4 :(得分:0)
你可以这样做
将字符串拆分为空格
string[] words = s.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word.Substring(0,2));
}
答案 5 :(得分:0)
这里有一些linq:
string s = "Hello to all";
var words = s.Split(' ');
var result = new string(words.SelectMany(w=>w.Take(2)).ToArray());
答案 6 :(得分:0)
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);
}
答案 7 :(得分:0)
string str = "Hello to all";
string result = str.Split().Select(word => word.Substring(0, 2)).Aggregate((aggr, next) => aggr + next);
答案 8 :(得分:0)
//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)));
答案 9 :(得分:0)
string word = "Hellow to all";
string result = "";
foreach(var item in word.Take(2))
{
result += item;
}