C# 使用IndexOf分隔句子中的单词
我试图在C#console中编写一个程序,基本上让用户输入一个句子,每个单词用逗号分隔,然后它会让控制台上的输出分别显示每个单词。下面是我正在尝试做的一个例子 请输入一个以逗号分隔的句子:C# 使用IndexOf分隔句子中的单词,c#,indexof,C#,Indexof,我试图在C#console中编写一个程序,基本上让用户输入一个句子,每个单词用逗号分隔,然后它会让控制台上的输出分别显示每个单词。下面是我正在尝试做的一个例子 请输入一个以逗号分隔的句子: 你好,我的名字是约翰 然后输出将如下所示 Hello, my, name, is, john my, name, is, john name, is, john is, john john 这是一个家庭作业,但是今天的课被取消了,所以我们从来没有上过这方面的课 根据我的阅读,你必须使用索引的方法,但到目前为
你好,我的名字是约翰 然后输出将如下所示
Hello, my, name, is, john
my, name, is, john
name, is, john
is, john
john
这是一个家庭作业,但是今天的课被取消了,所以我们从来没有上过这方面的课
根据我的阅读,你必须使用索引的方法,但到目前为止,它只是打印出索引编号,而不是实际的单词。这是我到目前为止得到的,它非常简单,但我才刚刚开始
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chapter_16_Sample_1
{
class Program
{
static void Main(string[] args)
{
string sentence;
Console.WriteLine("Please enter four words seperated by a comma");
sentence = Console.ReadLine();
int first = sentence.IndexOf(",");
Console.WriteLine("{0}", first);
Console.ReadLine();
}
}
}
就像我说的,它确实给了我正确的第一个逗号的索引号,但是如果我能找出如何提取整个单词,我想我能找出这个赋值。你得到了第一个逗号的索引,然后在控制台中显示它 您需要方法从用户输入中获取子字符串。
substring
方法将索引作为参数,然后返回从该索引开始直到字符串结尾的子字符串,除非您提供了参数
例如,此代码将在控制台中显示,John
:
string input = "Hello, John";
int index = input.IndexOf(',');
Console.WriteLine(input.Substring(index));
正如您所看到的,它还包括起始索引处的字符(在本例中为避免此情况,可以使用input.Substring(index+1)
而不是input.Substring(index)
现在,如果我们返回您的问题,您可以使用while
循环,然后获取从第一个逗号开始的子字符串,显示它并在每次迭代中更新用户输入的值。还可以使用变量保存字符串中第一个逗号的索引,因此当它变为-1
时,您将知道如果字符串中不存在逗号,则中断循环并显示最后一部分:
string userInput = Console.ReadLine();
int index = userInput.IndexOf(','); // get the index of first comma
while (index != -1) // keep going until there is no comma
{
// display the current value of userInput
Console.WriteLine(userInput);
// update the value of userInput
userInput = userInput.Substring(index + 1).Trim();
// update the value of index
index = userInput.IndexOf(',');
}
Console.WriteLine(userInput); // display the last part
注意:我还使用了方法从用户输入中删除尾随空格
您可以这样做:
- 读这个句子
idx
变量将保留由IndexOf
检索的最后一个逗号的位置。您可以使用IndexOf
的重载,指定下一个逗号的搜索开始索引IndexOf
在找不到值时将返回-1
,即停止循环的条件。
- 最后一步是使用方法
Substring
打印从位置idx+1
到字符串末尾的子字符串
代码是这样的。请试着理解它,如果你只是复制粘贴它,你不会学到任何东西。
Console.WriteLine("Please enter four words separated by a comma");
string sentence = Console.ReadLine();
Console.WriteLine(sentence);
int idx = -1;
while (true)
{
idx = sentence.IndexOf(',', idx + 1);
if (idx == -1) break;
Console.WriteLine(sentence.Substring(idx + 1));
}
你的代码在哪里?还有,如果课程取消了,他们还希望你做这个作业吗?对不起,我现在实际上正在写代码。根据电子邮件,我得到了做这个作业所需的所有信息,这些信息都在我们的阅读材料中,但我仍然没有完全理解。我编辑了上面的代码,内容不多我才刚刚开始。你必须使用Indexof吗?谢谢大家的帮助,你的解释帮助了很多,这比我想象的要容易。