【问题标题】:Separating words of a sentence using IndexOf [closed]使用 IndexOf 分隔句子的单词 [关闭]
【发布时间】:2014-04-28 01:51:53
【问题描述】:

我正在尝试在 C# 控制台中编写一个程序,该程序基本上让用户输入一个句子,每个单词用逗号分隔,然后控制台上的输出将单独显示每个单词。这是我正在尝试做的一个示例。

请输入一个逗号分隔的句子:
你好,我的名字是约翰

那么输出应该是这样的

Hello, my, name, is, john
my, name, is, john
name, is, john
is, john
john

这是一项家庭作业,但这一天的课程被取消了,所以我们从来没有上过这节课。

根据我的阅读,您必须使用 index of 方法,但到目前为止它只是打印出索引号而不是实际单词。这是我到目前为止所得到的,它非常简单,但我才刚刚开始。

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();
        }
    }
}

就像我说的那样,它确实给了我第一个逗号的正确索引号,但是如果我能弄清楚如何提取整个单词,我想我可以弄清楚这个作业。

【问题讨论】:

  • 你的代码在哪里?另外,如果课程被取消,他们还希望你做这个作业吗?
  • 对不起,我现在实际上正在编写代码。根据这封电子邮件,我在阅读材料中获得了完成这项任务所需的所有信息,但我仍然没有完全理解。我编辑了上面的代码,虽然不多,但我才刚刚开始。
  • 必须使用 Indexof 吗?

标签: c# indexof


【解决方案1】:

您正在获取第一次出现逗号的索引,然后将其显示在控制台中。

您需要String.Substring 方法从用户输入中获取子字符串。Substring 方法将索引作为参数,然后返回从该索引开始直到字符串结尾的子字符串,除非您提供count 参数。

例如,此代码将在控制台中显示, John

string input = "Hello, John";
int index = input.IndexOf(',');
Console.WriteLine(input.Substring(index));

如您所见,它还包括起始索引处的字符(在这种情况下为逗号,为了避免这种情况,您可以使用 input.Substring(index + 1) 而不是 input.Substring(index)

现在,如果我们返回您的问题,您可以使用while 循环,然后获取从第一个逗号开始的子字符串,显示它并在每次迭代时更新userInput 的值。还可以使用变量来保留字符串中第一个逗号的index,当它变为-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

注意:我还使用String.Trim 方法从userInput 中删除尾随空格。

【讨论】:

  • 感谢大家的帮助,您的解释帮助很大,这比我想象的要容易。
【解决方案2】:

你可以这样做:

  • 阅读句子。
  • 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));
}

【讨论】:

    猜你喜欢
    • 2020-07-13
    • 2019-01-24
    • 2011-04-20
    • 1970-01-01
    • 2016-10-07
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多