简体   繁体   English

字符串操作-可以做得更好吗?

[英]String manipulation - Can this be made better?

Right now we're hand rolling logins and one of the requirements is to have the login page notify the user which module they're going to login to. 现在,我们正在手动滚动登录,其中一项要求是让登录页面通知用户他们要登录哪个模块。 Now the only thing I have to work with that has the URL they're going to land on is in a query string such as this: 现在,我唯一需要使用的URL就是查询字符串,例如:

Request.QueryString["ReturnURL"]

With a value like this: 具有这样的值:

~/moduleFolder/SpecificPage.aspx

Now this is the method that I created that can break that URL up by the forward slash, take that segment seperate the words, capitalize the first word, remove the first slash, and assign it back to the label for display. 现在,这是我创建的方法,可以通过反斜杠将URL分解,以该段分隔单词,大写第一个单词,删除第一个斜杠,然后将其分配回标签以供显示。 An example of the code is below: 代码示例如下:

string incomingName = Request.QueryString["ReturnURL"].ToString();
int first = incomingName.IndexOf(@"/");
int last = incomingName.LastIndexOf(@"/");
string tempName = incomingName.Substring(first, last - first);
string seperatedName = Regex.Replace(tempName, "([a-z])([A-Z])", "$1 $2");
string upperCased = seperatedName.Replace("/", "");
string portalName = char.ToUpper(upperCased[0]) + upperCased.Substring(1);
lblPortalName.Text = portalName;    

Is there a cleaner or better way to write this code with out having so many different instances of a new string? 有没有一种更干净或更完善的方法来编写此代码,而又没有太多不同的新字符串实例?

Yeah, the cleaner way would be like this: 是的,更干净的方法是这样的:

private static string GetMiddleSegment(string URL)
{
    // you should probably use a library function for this kind of thing

    int first = URL.IndexOf(@"/");
    int last = URL.LastIndexOf(@"/");
    return URL.Substring(first + 1, last - first - 1); // this is correct, right?
}

private static string SeparateWords(string camelCase)
{
    return Regex.Replace(camelCase, "([a-z])([A-Z])", "$1 $2");
}

private static string Uppercase(string name)
{
    return char.ToUpper(name[0]) + name.Substring(1);
}

// ...

string incomingURL = Request.QueryString["ReturnURL"].ToString();
string nameSegment = GetMiddleSegment(incomingURL);
string displayName = Uppercase(SeparateWords(nameSegment));
lblPortalName.Text = displayName;

You'll notice that my code doesn't create less string instances. 您会注意到,我的代码并没有创建更少的字符串实例。 That's because there's absolutely no way that the amount of string instances created here has anything to do with your performance when serving a request. 那是因为绝对不可能在这里创建的字符串实例的数量与服务请求时的性能有关。

string url = "~/moduleFolder/SpecificPage.aspx";
string moduleFolder = url.Split('/')[1];
string separatedName = Regex.Replace(moduleFolder, "([a-z])([A-Z])", "$1 $2");
string portalName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(separatedName);

I wouldn't change it. 我不会改变。 At best you'll save a few lines of code, but as it is, this code is probably more readable since this allows for descriptive names of the string at each step of manipulation. 充其量您可以节省几行代码,但实际上,此代码可能更具可读性,因为这允许在每个操作步骤中使用字符串的描述性名称。

Though you might look into library url functions instead of implementing your own. 虽然您可能会研究库的url函数,而不是自己实现。

I would write the code that gets the part between the first and second /s like this: 我将编写这样的代码来获得第一个和第二个/ s之间的部分:

var tempName = incomingName.Split('/').Last();

This is quite terser and IMO no harder to understand. 这是相当麻烦的,IMO也就不难理解了。 Plus, it saves you the trouble of doing 另外,它省去了您做麻烦的事情

string upperCased = seperatedName.Replace("/", "");

so the end result is 3 lines shorter without loss of readability. 因此最终结果缩短了3行,而不会损失可读性。

Edit: 编辑:

Simplified the Split call after the OP's comment that there will only be two slashes. 在OP声明只有两个斜杠之后,简化了Split调用。 The .Last() call can of course be substituted with [1] , although personally I prefer the way .Last() reads. .Last()调用当然可以用[1]代替,尽管我个人更喜欢.Last()读取方式。 It conveys intent more clearly than a magic number, especially if you are not the author of the code. 与魔术数字相比,它传达的意图更清晰,尤其是如果您不是代码的作者。

Based on RedFilter's regular expression you could created simple extension methods like: 根据RedFilter的正则表达式,您可以创建简单的扩展方法,例如:

private static string UrlModuleName(this string url)
{
    return Regex.Replace(url.Split('/')[1], "([a-z])([A-Z])",
                         "$1 $2").ToTitleCaseInvariant();
}
private static string ToTitleCaseInvariant(this string input)
{
    return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(input);
}

This is a good idea to get it simple . 让它变得简单是一个好主意

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM