how to check the condition in asp.net for string array - c#

I have to check the condition in asp.net for string array
The conditions is I can either have two values 360__image.jpg and image.jpg.
I have to return the correct value from the condition
If the string has 360_image.jpg I have to return only image.jpg and cutting 360_
If the string is image.jpg I have to return the same image.jpg
Code
public string splitString(string str)
{
string[] FileName = str.Split('_');
if (FileName[2] != "")
{
return FileName[2];
}
else
{
return FileName[0];
}
}
The problem with above code is I am getting the error
Index was outside the bounds of the array

You should check for length before accessing element from the array, that is why you are getting the exception, since split probably resulted in array of two elements.
Not exactly sure about your requirement but I think you can simplify your method as:
public string splitString(string str)
{
if (str.Contains("_")) //or check for 360__
return str.Substring(str.LastIndexOf('_') + 1);
else
return str;
}

You can use LastIndexOf:
public string splitString(string str)
{
return str.Substring(str.LastIndexOf('_') + 1);
}
Or even use LINQ Last:
public string splitString(string str)
{
return str.Split('_').Last();
}

Array has 2 elements , means idexes 0 and 1.
But you have taken into your code as FileName[2] .
This 2nd index may be wrong thats why error is comming. It may be 1.
Try with:
public string splitString(string str)
{
string[] FileName = str.Split('_');
if (FileName[1] != "")
{
return FileName[1];
}
else
{
return FileName[0];
}
}

Related

Confusing Switch/Case results

Of course before posting this error I searched the heck out it. The code below returns: error CS0029: Cannot implicitly convert type 'bool' to 'string' in two spots. Am I misunderstanding why the code below isn't returning a string? Thinking to myself what advice Stack Overflow might give I've tried my best to explicitly cast to a string but have only managed to confuse myself.
public static class Bob
{
public static string Response(string statement)
{
string teststring = statement;
bool IsAllUpper(string input)
{
for (int i = 0; i < input.Length; i++)
{
if (Char.IsLetter(input[i]) && !Char.IsUpper(input[i]))
return false;
}
return true;
}
switch(teststring)
{
case IsAllUpper(teststring) && teststring.EndsWith("?"):
string final1 = "Calm down, I know what I'm doing!";
return final1;
case teststring.EndsWith("?"):
string final2 = "Sure";
return final2;
default:
string final3 = "Whatever.";
return final3;
}
}
public static void Main()
{
string input = "This is the end";
Console.WriteLine("{0}", Response(input));
}
}
With switch(teststring) you're asking the code to switch on string values, e.g. "foo" and "bar". However, your cases are boolean values: IsAllUpper(teststring) and teststring.EndsWith("?") both return booleans.
Consider replacing the switch block with if statements, something like
if (IsAllUpper(teststring) && teststring.EndsWith("?")) {
string final1 = "Calm down, I know what I'm doing!";
return final1;
}
if (teststring.EndsWith("?")) {
string final2 = "Sure";
return final2;
}
string final3 = "Whatever.";
return final3;
or, for maximum conciseness obscurity, the one-liner:
return teststring.EndsWith("?") ? (IsAllUpper(teststring) ? "Calm down, I know what I'm doing!" : "Sure") : "Whatever."

How to find how many string in other string

I randomly trying to make this code works. The problem that I have is I can't find the string in some string, because char only takes one character.
Is there another way to do it?
e.g. I can find how many char "e" in "excellent", But I can't find "ll". It'll give me error.
The code which I use:
try
{
int count = label1.Text.Split(Convert.ToChar(textBox1.Text)).Length - 1;
MessageBox.Show(count.ToString());
}
catch
{
messagebox.show("error");
}
Thats why I am using try to catch the error.
This is because you use Convert.ToChar(...) which is supposed to take only convertible string to char (that is, consists of a single character, but "ll" consists of two characters).
You could create an extension for string to do what you want:
public static class StringExtensions {
public static List<int> AllIndexesOf(this string str, string value) {
if (String.IsNullOrEmpty(value))
throw new ArgumentException("the string to find may not be empty", "value");
List<int> indexes = new List<int>();
for (int index = 0; ; index += value.Length) {
index = str.IndexOf(value, index);
if (index == -1)
return indexes;
indexes.Add(index);
}
}
}
And then just use it like:
int count = label1.Text.AllIndexesOf(textBox1.Text).Count;

C# TrimStart with string parameter

I'm looking for String extension methods for TrimStart() and TrimEnd() that accept a string parameter.
I could build one myself but I'm always interested in seeing how other people do things.
How can this be done?
To trim all occurrences of the (exactly matching) string, you can use something like the following:
TrimStart
public static string TrimStart(this string target, string trimString)
{
if (string.IsNullOrEmpty(trimString)) return target;
string result = target;
while (result.StartsWith(trimString))
{
result = result.Substring(trimString.Length);
}
return result;
}
TrimEnd
public static string TrimEnd(this string target, string trimString)
{
if (string.IsNullOrEmpty(trimString)) return target;
string result = target;
while (result.EndsWith(trimString))
{
result = result.Substring(0, result.Length - trimString.Length);
}
return result;
}
To trim any of the characters in trimChars from the start/end of target (e.g. "foobar'#"#';".TrimEnd(";#'") will return "foobar") you can use the following:
TrimStart
public static string TrimStart(this string target, string trimChars)
{
return target.TrimStart(trimChars.ToCharArray());
}
TrimEnd
public static string TrimEnd(this string target, string trimChars)
{
return target.TrimEnd(trimChars.ToCharArray());
}
TrimStart and TrimEnd takes in an array of chars. This means that you can pass in a string as a char array like this:
var trimChars = " .+-";
var trimmed = myString.TrimStart(trimChars.ToCharArray());
So I don't see the need for an overload that takes a string parameter.
I thought the question was trying to trim a specific string from the start of a larger string.
For instance, if I had the string "hellohellogoodbyehello", if you tried to call TrimStart("hello") you would get back "goodbyehello".
If that is the case, you could use code like the following:
string TrimStart(string source, string toTrim)
{
string s = source;
while (s.StartsWith(toTrim))
{
s = s.Substring(toTrim.Length - 1);
}
return s;
}
This wouldn't be super-efficient if you needed to do a lot of string-trimming, but if its just for a few cases, it is simple and gets the job done.
To match entire string and not allocate multiple substrings, you should use the following:
public static string TrimStart(this string source, string value, StringComparison comparisonType)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
int valueLength = value.Length;
int startIndex = 0;
while (source.IndexOf(value, startIndex, comparisonType) == startIndex)
{
startIndex += valueLength;
}
return source.Substring(startIndex);
}
public static string TrimEnd(this string source, string value, StringComparison comparisonType)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
int sourceLength = source.Length;
int valueLength = value.Length;
int count = sourceLength;
while (source.LastIndexOf(value, count, comparisonType) == count - valueLength)
{
count -= valueLength;
}
return source.Substring(0, count);
}
from dotnetperls.com,
Performance
Unfortunately, the TrimStart method is not heavily optimized. In
specific situations, you will likely be able to write character-based
iteration code that can outperform it. This is because an array must
be created to use TrimStart.
However: Custom code would not necessarily require an array. But for
quickly-developed applications, the TrimStart method is useful.
There is no built in function in C# - but you can write your own extension methods which I will show you below - they can be used like the builtin ones to trim characters, but here you can use strings to trim.
Note that with IndexOf / LastIndexOf, you can choose if it is case sensitive / culture sensitive or not.
I have implemented the feature "repetitive trims" as well (see the optional parameters).
Usage:
// myStr: the string that needs to be trimmed
// trimStr: the string to trim from myStr
var trimmed1 = myStr.TrimStart(trimStr);
var trimmed2 = myStr.TrimEnd(trimStr);
var trimmed3 = myStr.TrimStr(trimStr);
var trimmed4 = myStr.Trim(trimStr);
There is one function TrimStr(..) trimming from the start and from the end of the string, plus three functions implementing .TrimStart(...), .TrimEnd(...) and .Trim(..) for compatibility with the .NET trims:
Try it in DotNetFiddle
public static class Extension
{
public static string TrimStr(this string str, string trimStr,
bool trimEnd = true, bool repeatTrim = true,
StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
{
int strLen;
do
{
strLen = str.Length;
{
if (trimEnd)
{
if (!(str ?? "").EndsWith(trimStr)) return str;
var pos = str.LastIndexOf(trimStr, comparisonType);
if ((!(pos >= 0)) || (!(str.Length - trimStr.Length == pos))) break;
str = str.Substring(0, pos);
}
else
{
if (!(str ?? "").StartsWith(trimStr)) return str;
var pos = str.IndexOf(trimStr, comparisonType);
if (!(pos == 0)) break;
str = str.Substring(trimStr.Length, str.Length - trimStr.Length);
}
}
} while (repeatTrim && strLen > str.Length);
return str;
}
// the following is C#6 syntax, if you're not using C#6 yet
// replace "=> ..." by { return ... }
public static string TrimEnd(this string str, string trimStr,
bool repeatTrim = true,
StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> TrimStr(str, trimStr, true, repeatTrim, comparisonType);
public static string TrimStart(this string str, string trimStr,
bool repeatTrim = true,
StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> TrimStr(str, trimStr, false, repeatTrim, comparisonType);
public static string Trim(this string str, string trimStr, bool repeatTrim = true,
StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> str.TrimStart(trimStr, repeatTrim, comparisonType)
.TrimEnd(trimStr, repeatTrim, comparisonType);
}
Now you can just use it like
Console.WriteLine("Sammy".TrimEnd("my"));
Console.WriteLine("Sammy".TrimStart("Sam"));
Console.WriteLine("moinmoin gibts gips? gips gibts moin".TrimStart("moin", false));
Console.WriteLine("moinmoin gibts gips? gips gibts moin".Trim("moin").Trim());
which creates the output
Sam
my
moin gibts gips? gips gibts moin
gibts gips? gips gibts
In the last example, the trim function does a repetitive trim, trimming all occurances of "moin" at the beginning and at the end of the string. The example before just trims "moin" only once from the start.
I'm assuming you mean that, for example, given the string "HelloWorld" and calling the function to 'trim' the start with "Hello" you'd be left with "World". I'd argue that this is really a substring operation as you're removing a portion of the string of known length, rather than a trim operation which removes an unknown length of string.
As such, we created a couple of extension methods named SubstringAfter and SubstringBefore. It would be nice to have them in the framework, but they aren't so you need to implement them yourselves. Don't forget to have a StringComparison parameter, and to use Ordinal as the default if you make it optional.
If you did want one that didn't use the built in trim functions for whatever reasons, assuming you want an input string to use for trimming such as " ~!" to essentially be the same as the built in TrimStart with [' ', '~', '!']
public static String TrimStart(this string inp, string chars)
{
while(chars.Contains(inp[0]))
{
inp = inp.Substring(1);
}
return inp;
}
public static String TrimEnd(this string inp, string chars)
{
while (chars.Contains(inp[inp.Length-1]))
{
inp = inp.Substring(0, inp.Length-1);
}
return inp;
}
Function to trim start/end of a string with a string parameter, but only once (no looping, this single case is more popular, loop can be added with an extra param to trigger it) :
public static class BasicStringExtensions
{
public static string TrimStartString(this string str, string trimValue)
{
if (str.StartsWith(trimValue))
return str.TrimStart(trimValue.ToCharArray());
//otherwise don't modify
return str;
}
public static string TrimEndString(this string str, string trimValue)
{
if (str.EndsWith(trimValue))
return str.TrimEnd(trimValue.ToCharArray());
//otherwise don't modify
return str;
}
}
As mentioned before, if you want to implement the "while loop" approach, be sure to check for empty string otherwise it can loop forever.

Remove characters before character "."

How effectively remove all character in string that placed before character "."?
Input:
Amerika.USA
Output:
USA
You can use the IndexOf method and the Substring method like so:
string output = input.Substring(input.IndexOf('.') + 1);
The above doesn't have error handling, so if a period doesn't exist in the input string, it will present problems.
You could try this:
string input = "lala.bla";
output = input.Split('.').Last();
string input = "America.USA"
string output = input.Substring(input.IndexOf('.') + 1);
String input = ....;
int index = input.IndexOf('.');
if(index >= 0)
{
return input.Substring(index + 1);
}
This will return the new word.
Extension methods I commonly use to solve this problem:
public static string RemoveAfter(this string value, string character)
{
int index = value.IndexOf(character);
if (index > 0)
{
value = value.Substring(0, index);
}
return value;
}
public static string RemoveBefore(this string value, string character)
{
int index = value.IndexOf(character);
if (index > 0)
{
value = value.Substring(index + 1);
}
return value;
}
public string RemoveCharactersBeforeDot(string s)
{
string splitted=s.Split('.');
return splitted[splitted.Length-1]
}
A couple of methods that, if the char does not exists, return the original string.
This one cuts the string after the first occurrence of the pivot:
public static string truncateStringAfterChar(string input, char pivot){
int index = input.IndexOf(pivot);
if(index >= 0) {
return input.Substring(index + 1);
}
return input;
}
This one instead cuts the string after the last occurrence of the pivot:
public static string truncateStringAfterLastChar(string input, char pivot){
return input.Split(pivot).Last();
}

What is the most elegant way to implement GetTextAfterMarker()

Here is another old function I have from my C# 1 days, what would be a more elegant way to write it:
//method: gets the text in a string in front of a marker, if marker is not there, then return empty string
//example: GetTextAfterMarker("documents/jan/letter043.doc","/") returns "documents"
//example: GetTextAfterMarker("letter043.doc","/") returns ""
//rank:8
public static string GetTextAfterMarker(string line, string marker) {
string r = "";
int pos = line.IndexOf(marker);
if(pos != -1) {
r = line.Substring(pos+(marker.Length),line.Length-pos-(marker.Length));
} else {
r = "";
}
return r;
}
I find the name somewhat strange, given that it should return the text appearing before the first marker. But this one does the same job, I think (I took the liberty to change the name):
public static string GetTextBeforeMarker(string line, string marker)
{
if (line == null)
{
throw new ArgumentNullException("line");
}
if (marker == null)
{
throw new ArgumentNullException("marker");
}
string result = line.Split(new string[] { marker }, StringSplitOptions.None)[0];
return line.Equals(result) ? string.Empty : result;
}
Explanation: split the string into an array using the marker as split argument. If the first element of the result is the same as the input, the marker was not in the string, so we return an empty string, otherwise we return the first element (which is the text up to the first occurrence of the marker).
Am I missing something? Wouldn't this be more simple? Also I prefer Substring to Split.
public static string GetTextAfterMarker(string line, string marker) {
int pos = line.IndexOf(marker);
if (pos == -1)
return string.Empty;
return line.Substring(0,pos);
}
public static string GetTextBeforeMarker(string line, string marker) {
return GetTextAfterMarker(string line, string marker);
}
You could use regular expressions:
public static string GetTextBeforeMarker(string line, string marker)
{
if (String.IsNullOrEmpty(line))
throw new ArgumentException("line is null or empty.", "line");
if (String.IsNullOrEmpty(marker))
throw new ArgumentException("marker is null or empty.", "marker");
string EscapedMarker = Regex.Escape(marker);
return Regex.Match(line, "([^" + EscapedMarker + "]+)" + EscapedMarker).Groups[1].Value;
}

Categories

Resources