[英]c# extracting words
i have following piece of code with me iam spliting the words using only one space and the output is 我有以下一段代码,我仅使用一个空格将单词拆分,输出为
output: 输出:
when ambition ends happiness begins
But i want split the words after two spaces i mean my output should be like this: 但是我想在两个空格后分开单词,这意味着我的输出应该像这样:
when ambition ends happiness begins
string vj = "when ambiton ends happiness begins";
List<string> k = new List<string>();
char ch = ' ';
string[] arr = vj.Split(ch);
foreach (string r in arr)
{
Response.Write(r + "<br/>");
}
As this is marked homework, I will give a hint: 由于这是标记为作业,因此我将给出一个提示:
Here's a solution with regular expressions: 这是带有正则表达式的解决方案:
// Loosely: a word, followed by another word if available
Regex regex = new Regex(@"\S+( \S+)?");
string[] splits = regex.Matches(inputText)
.Cast<Match>()
.Select(match => match.Value)
.ToArray();
像现在一样拆分它,然后循环生成的数组,并使用标准的for
循环将它们连接在一起。
You're gonna have to go manual on this one, searching for the space-character in the string, and keeping a counter. 您将必须手动编写该代码,在字符串中搜索空格字符,并保留一个计数器。 You'll have to remember the indices of the space-characters you'll want to split from, and use the .Substring(startindex, length) method for extracting the separate parts. 您必须记住要拆分的空格字符的索引,并使用.Substring(startindex,length)方法提取单独的部分。
string vj = "when ambiton ends happiness begins";
List<string> k = new List<string>();
char ch = ' ';
string[] arr = vj.Split(ch);
bool flag=false;
foreach (string r in arr)
{
if(flag)
{
Response.Write(r + "<br/>");
flag=false;
}
else
{
Response.Write(r + " ");
flag=true;
}
}
The above is good for the case you specified (skipping a single space). 上面的内容适合您指定的情况(跳过单个空格)。
Though not necessary, but if you want it all wrapped up, Here : 虽然不是必需的,但是如果您希望将其全部打包,请在此处:
string myString = "when ambiton ends happiness begins";
bool flag=false;
foreach (string item in myString.Split(ch))
Response.Write(item + flag=!flag?" ":"<br/>");
You can just add a bool indicating whether or not you should add "/br", call it breakLine. 您可以仅添加一个布尔值,指示是否应添加“ / br”,将其称为breakLine。
Now at each iteration check if it's true - if so add "/br", otherwise don't. 现在,在每次迭代中检查是否为真-如果是,则添加“ / br”,否则不添加。 finally negate it at each iteration. 最终在每次迭代时将其取反。
Implementation is left as an exercise (-: 实施留作练习(-:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.