字符串中的特殊字符 [英] Special Characters in String

查看:101
本文介绍了字符串中的特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

这是用于获取第一操作数,第二操作数和运算符的代码;

Hello all,

this is code for getting First Operand, Second Operand and Operator;

string op1 = screentxt.Text.Split('+')[0].ToString();

            int index = screentxt.Text.IndexOf('+');
            string op2 = screentxt.Text.Substring(index + 1);

            char[] str = screentxt.Text.Trim().ToCharArray();
            string op="";

            foreach (char c in str)
            {
                if (char.IsSymbol(c))
                    op = c.ToString();
            }


如果我的字符串包含"+"号,那么它将返回我"+",但不会返回其他字符,例如-,*,/.帮助消除此错误..


If my string contains ''+'' sign then it return me ''+'' but not for the other chars like -, *, /. Help to remove this error..

推荐答案

克鲁纳尔,

在下面的行中找到相同的内容.

Hi Krunal,

Use the below line to find the same.

if(screentxt.Text.Contains("+"))
{
  string op1 = screentxt.Text.Split('+')[0].ToString();
  int index = screentxt.Text.IndexOf('+');
  string op2 = screentxt.Text.Substring(index + 1);
  string op= "+";
}



上面的代码块仅在您的文本框包含+号时执行.



Above code block only execute when your textbox contains + sign.


如果我正确理解,则可以从字符串中提取字符(+,*等).

但是,您的char.IsSymbol仅对+符号返回true,而对其他符号则不返回.

这是预期的行为,因为IsSymbol有点奇怪.仅当字符属于以下Unicode类别之一时,它才返回true. MathSymbol,CurrencySymbol,ModifierSymbol和OtherSymbol.

猜猜,*,-不属于此类.用以下代码检查自己

If I understand correctly, you are able to extract character (+, * etc) from a string.

But Your char.IsSymbol returns true only for + symbol and not for others.

This is expected behaviour as IsSymbol works little strangely. It returns true only if character belonngs to one of the following Unicode categories. MathSymbol, CurrencySymbol, ModifierSymbol, and OtherSymbol.

And guess what, * , - doesn''t fall in any of this category. Check yourself with following code

Console.WriteLine(Char.GetUnicodeCategory('*').ToString());

Console.WriteLine(Char.GetUnicodeCategory('-').ToString());



最好的识别方法是将开关盒和手动字符代码进行比较.

希望对您有帮助
Milind



The best way to identify then is by putting switch case and manual character code comparison.

Hope that helps
Milind


使用系统;
使用System.CodeDom;
使用System.CodeDom.Compiler;
使用Microsoft.CSharp;
使用System.Text;
使用System.Reflection;

///< summary>
///Class1的摘要描述.
///
公共类评估器
{
#region建设
公共评估者(EvaluatorItem []项目)
{
ConstructEvaluator(items);
}

公共计算器(类型returnType,字符串表达式,字符串名称)
{
EvaluatorItem []项目= {新的EvaluatorItem(returnType,表达式,名称)};
ConstructEvaluator(items);
}

公共评估者(EvaluatorItem项目)
{
EvaluatorItem []项目= {项目};
ConstructEvaluator(items);
}

private void ConstructEvaluator(EvaluatorItem []项目)
{
ICodeCompiler comp =(new CSharpCodeProvider().CreateCompiler());
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.ReferencedAssemblies.Add("system.data.dll");
cp.ReferencedAssemblies.Add("system.xml.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;

StringBuilder代码=新的StringBuilder();
code.Append(正在使用System; \ n");
code.Append("using System.Data; \ n");
code.Append("using System.Data.SqlClient; \ n");
code.Append("using System.Data.OleDb; \ n");
code.Append("using System.Xml; \ n");
code.Append(命名空间ADOGuy {\ n");
code.Append(公共类_Evaluator {\ n");
foreach(项目中的EvaluatorItem项目)
{
code.AppendFormat("public {0} {1}()",
item.ReturnType.Name,
item.Name);
code.Append("{");
code.AppendFormat("return({0});",item.Expression);
code.Append(} \ n");
}
code.Append(}}");

CompilerResults cr = comp.CompileAssemblyFromSource(cp,code.ToString());
如果(cr.Errors.HasErrors)
{
StringBuilder错误=新的StringBuilder();
error.Append(错误编译表达式:");
foreach(在cr.Errors中为CompilerError err)
{
error.AppendFormat("{0} \ n",err.ErrorText);
}
抛出新的Exception("Error Compiling Expression:" + error.ToString());
}
程序集a = cr.CompiledAssembly;
_Compiled = a.CreateInstance("ADOGuy._Evaluator");
}
#endregion

#region公众成员
public int EvaluateInt(字符串名称)
{
return(int)Evaluate(name);
}

公共字符串EvaluateString(字符串名称)
{
return(string)Evaluate(name);
}

公共布尔EvaluateBool(字符串名称)
{
return(bool)Evaluate(name);
}

公共对象Evaluate(字符串名称)
{
MethodInfo mi = _Compiled.GetType().GetMethod(name);
返回mi.Invoke(_Compiled,null);
}
#endregion

#region静态成员
静态公共double EvaluateToDouble(字符串代码)
{
评估程序eval =新的评估程序(typeof(double),code,staticMethodName);
return(double)eval.Evaluate(staticMethodName);
}

静态公共int EvaluateToInteger(字符串代码)
{
评估程序eval =新的评估程序(typeof(int),代码,staticMethodName);
return(int)eval.Evaluate(staticMethodName);
}

静态公共字符串EvaluateToString(字符串代码)
{
评估程序eval =新的评估程序(typeof(string),代码,staticMethodName);
return(string)eval.Evaluate(staticMethodName);
}

静态公共布尔EvaluateToBool(字符串代码)
{
评估程序eval =新的评估程序(typeof(bool),代码,staticMethodName);
return(bool)eval.Evaluate(staticMethodName);
}

静态公共对象EvaluateToObject(字符串代码)
{
评估程序eval =新的评估程序(typeof(object),代码,staticMethodName);
返回eval.Evaluate(staticMethodName);
}
#endregion

#region私人
const string staticMethodName ="__foo";
类型_CompiledType = null;
对象_Compiled = null;
#endregion
}

公共类EvaluatorItem
{
公共EvaluatorItem(类型returnType,字符串表达式,字符串名称)
{
ReturnType = returnType;
表达式=表达式;
名称=名称;
}

public Type ReturnType;
公共字符串名称;
公共字符串表达式;
}



/*
//使用以下代码执行...

字符串sAnswer = Evaluator.EvaluateToDouble("10 + 15 + 20-18 * 2/8").ToString();
*/
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Text;
using System.Reflection;

/// <summary>
/// Summary description for Class1.
///
public class Evaluator
{
#region Construction
public Evaluator(EvaluatorItem[] items)
{
ConstructEvaluator(items);
}

public Evaluator(Type returnType, string expression, string name)
{
EvaluatorItem[] items = { new EvaluatorItem(returnType, expression, name) };
ConstructEvaluator(items);
}

public Evaluator(EvaluatorItem item)
{
EvaluatorItem[] items = { item };
ConstructEvaluator(items);
}

private void ConstructEvaluator(EvaluatorItem[] items)
{
ICodeCompiler comp = (new CSharpCodeProvider().CreateCompiler());
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.ReferencedAssemblies.Add("system.data.dll");
cp.ReferencedAssemblies.Add("system.xml.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;

StringBuilder code = new StringBuilder();
code.Append("using System; \n");
code.Append("using System.Data; \n");
code.Append("using System.Data.SqlClient; \n");
code.Append("using System.Data.OleDb; \n");
code.Append("using System.Xml; \n");
code.Append("namespace ADOGuy { \n");
code.Append(" public class _Evaluator { \n");
foreach (EvaluatorItem item in items)
{
code.AppendFormat(" public {0} {1}() ",
item.ReturnType.Name,
item.Name);
code.Append("{ ");
code.AppendFormat(" return ({0}); ", item.Expression);
code.Append("}\n");
}
code.Append("} }");

CompilerResults cr = comp.CompileAssemblyFromSource(cp, code.ToString());
if (cr.Errors.HasErrors)
{
StringBuilder error = new StringBuilder();
error.Append("Error Compiling Expression: ");
foreach (CompilerError err in cr.Errors)
{
error.AppendFormat("{0}\n", err.ErrorText);
}
throw new Exception("Error Compiling Expression: " + error.ToString());
}
Assembly a = cr.CompiledAssembly;
_Compiled = a.CreateInstance("ADOGuy._Evaluator");
}
#endregion

#region Public Members
public int EvaluateInt(string name)
{
return (int)Evaluate(name);
}

public string EvaluateString(string name)
{
return (string)Evaluate(name);
}

public bool EvaluateBool(string name)
{
return (bool)Evaluate(name);
}

public object Evaluate(string name)
{
MethodInfo mi = _Compiled.GetType().GetMethod(name);
return mi.Invoke(_Compiled, null);
}
#endregion

#region Static Members
static public double EvaluateToDouble(string code)
{
Evaluator eval = new Evaluator(typeof(double), code, staticMethodName);
return (double)eval.Evaluate(staticMethodName);
}

static public int EvaluateToInteger(string code)
{
Evaluator eval = new Evaluator(typeof(int), code, staticMethodName);
return (int)eval.Evaluate(staticMethodName);
}

static public string EvaluateToString(string code)
{
Evaluator eval = new Evaluator(typeof(string), code, staticMethodName);
return (string)eval.Evaluate(staticMethodName);
}

static public bool EvaluateToBool(string code)
{
Evaluator eval = new Evaluator(typeof(bool), code, staticMethodName);
return (bool)eval.Evaluate(staticMethodName);
}

static public object EvaluateToObject(string code)
{
Evaluator eval = new Evaluator(typeof(object), code, staticMethodName);
return eval.Evaluate(staticMethodName);
}
#endregion

#region Private
const string staticMethodName = "__foo";
Type _CompiledType = null;
object _Compiled = null;
#endregion
}

public class EvaluatorItem
{
public EvaluatorItem(Type returnType, string expression, string name)
{
ReturnType = returnType;
Expression = expression;
Name = name;
}

public Type ReturnType;
public string Name;
public string Expression;
}



/*
// USE THE FOLLOWING CODE TO EXECUTE...

string sAnswer = Evaluator.EvaluateToDouble("10+15+20-18*2/8").ToString();
*/


这篇关于字符串中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆