我需要一个方法,它返回以第一个字符开头的字符串中的每个其他字符。例如,使用(“Java-language”)的方法调用返回“Jv-agae。”
private static void NewMethod(string word)
{
// here comes the code
}
答案 0 :(得分:10)
var str = "Java-language";
var xx = new string(str.Where((ch, index) => index % 2 == 0).ToArray());
Console.WriteLine(xx);
或者这个:
var xx = string.Join<char>("", str.Where((ch, index) => (index & 1) == 0));
答案 1 :(得分:6)
可能与其他人差别不大: - )
protected static IEnumerable<char> EverySecondChar(string word)
{
for(int i = 0; i < word.Length; i += 2)
yield return word[i];
}
string result = new string(EverySecondChar("Java-language").ToArray());
答案 2 :(得分:2)
以下是我的建议:
private string TakeEverySecondChar(string input)
{
var result = string.Empty;
for (int i = 0; i < input.Length; i+=2)
{
result += input.Substring(i, 1);
}
return result;
}
答案 3 :(得分:1)
Console.Clear();
string Lang = "Java-language";
string[] LangArr = new string[Lang.Length];
char LangChar;
for (int i = 0; i < Lang.Length; i++)
{
LangChar = Lang[i];
LangArr[i] = LangChar.ToString();
}
for (int i = 0; i < LangArr.Length; i++)
{
Console.Write(LangArr[i]);
i++;
}
Console.ReadLine();
答案 4 :(得分:0)
public String strip2ndchar(string text)
{
string final="";
int i = 0;
foreach (char a in text.ToCharArray())
{
if (i % 2 == 0)
final += a;
i++;
}
return final;
}