如何从字符串中删除最后一个单词? [英] How can I remove last word from a string ?

查看:139
本文介绍了如何从字符串中删除最后一个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有像Karim或Rahim去寻找OR的字符串



我想得到的结果是Karim或Rahim去了



  string  str =   Karim OR Rahim OR Motin代表OR; 







我想删除最后一个字或者甚至可以在OR之后有空格或有时它不能。



请记住有时候最后一个单词可以是OR,有时它可以是AND。



所以请给出一个解决方案如何删除最后一个单词?



我正在通过此代码进行操作。通过使用以下代码,我可以得到最后一个字。但我不

解决方案

如果最后一个字总是AND或OR那么它很简单,只需使用正则表达式:

  public   static 正则表达式regex =  new 正则表达式( (\\\\ +(AND | OR)\\ t *)

);
...
string result = regex.Replace(InputText, < span class =code-string>);






首先要明白空格('')是字符的分隔符,使它们成为单词。





1.删除最后一个来自字符串的额外空间..

 字符串 str =    Karim OR Rahim OR Motin为OR; 
string strTrimmed = str.Trim();





2.然后通过找到最后一个空格来获取子字符串('')



  string  finalString = strTrimmed.Substring(strTrimmed.LastIndexOf( ,strTrimmed.Length); 



LastIndexOf() - >用于查找指定字符的最后一个索引位置..





谢谢

Magesh M


I have string like "Karim or Rahim goes for OR "

I want to get result as "Karim or Rahim goes for"

string str="Karim OR Rahim OR Motin goes for OR ";




I want to remove the last word OR even there can have a space after OR or sometimes it can't.

Please keep in mind that sometimes the last word can be "OR" and sometimes it can be "AND".

So please give a solution how can I remove last word ?

I am triying through this code. By using following code I can get last word. But I don

解决方案

If the last word is always AND or OR then it's pretty simple, just use a regex:

public static Regex regex = new Regex("(\\s+(AND|OR)\\s*)


"); ... string result = regex.Replace(InputText,"");


Hi,

First understand that space(' ') is the separator of characters to make those as words.


1.Remove the last extra space from your string..

string str="Karim OR Rahim OR Motin goes for OR ";
      string strTrimmed=str.Trim();



2.Then Get the substring by finding the last space(' ')

string finalString= strTrimmed.Substring(strTrimmed.LastIndexOf(" ",strTrimmed.Length);


LastIndexOf() -- > is used to find the last index position of a specified character..


Thanks
Magesh M


这篇关于如何从字符串中删除最后一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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