【问题标题】:find first character of string查找字符串的第一个字符
【发布时间】:2018-01-19 01:01:14
【问题描述】:

特别是字符串,我必须比较第一个字符 字符串的“x”(任意)然后返回所有字符串,否则返回空白,其他条件是如果有第四个字符是“-”则返回字符串

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace @string
{
    class Program
    {
        static void Main(string[] args)
        {
            string myString = "bhargav m patel".Trim();

            Console.Write("Type a char : ");
            string mychar = Console.ReadLine();

            if (myString.StartsWith("[a-zA-Z]").Equals(mychar))
            {
                Console.WriteLine("true");
            }
            else
            {
                Console.WriteLine("false");
            }

            Console.ReadLine();
        }
    }
}

【问题讨论】:

  • 这段代码有什么问题?
  • 我无法比较第一个字符。
  • if (myString.StartsWith(myChar)) 有什么问题?
  • 没试过..会检查。 tnx @ken
  • 没有任何字符串方法支持正则表达式,因此您的问题。只需做 StartsWith("x")

标签: c# .net linq oop


【解决方案1】:

嗯,我试过了,效果很好。适合你的情况吗?

static void Main(string[] args)
{
    string myString = "bhargav m patel".Trim();

    Console.Write("Type a char : ");
    string mychar = Console.ReadLine();

    if (myString.StartsWith(mychar))
        Console.WriteLine("true");
    else 
       Console.WriteLine("false");

    Console.ReadLine();
}

【讨论】:

    【解决方案2】:

    我不确定我得到了你想要的,但是: 如果你想比较字符串第一个字符和用户输入的字符,你可以这样做:

    if (myString.StartsWith(mychar))
            {
                Console.WriteLine("true");
            }
    

    【讨论】:

      猜你喜欢
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 2019-09-22
      • 2013-09-25
      相关资源
      最近更新 更多