How to use .Substring? - c#

I know that this looks like a noob question, but I don't know what's going on that I keep getting wrong values when using the .substring. I have used it in java like this
text = "stackoverflow"
text1 = text.substring(start, end);
where start can be any number < text.length and it works perfectly. Example
text1 = text.substring(9, text.length);
Should give me "flow" but if I try that exact code in Visual Basic it gives me the full text "stackoverflow" so... what am I doing wrong?
Here's my code for it:
TextBox2.Text = bin.Substring(9, text.length)

The second parameter is not end position, but length of desired output string:
'Declaration
Public Function Substring ( _
startIndex As Integer, _
length As Integer _
) As String
This should return "flow":
TextBox2.Text = bin.Substring(9,4)

Related

Concatenation issue when using label in WinForms C#

There is a code part in my program. Lets say buf.Substring(0, 4) is a string which is 326 for that moment in the loop. String buf.Substring(0, 4) is updated in a for loop.
if (buf.Substring(0, 4).Equals("GG:"))
{
label22.Text = buf.Substring(4) + "Z" ;
}
This outputs on label22 as:
326
Z
If you replace it as
label22.Text = "Z" + buf.Substring(4);
then it concatenates properly as:
Z326
But I want the output to be:
326Z
Whatever I tried it dodn't work. I tried concatenating different ways or sizing label width very long ect. What could be the problem here?
You could try trimming the output of buf.Substring(4) like this
String output = buf.Substring(4).Trim(new char[] {'\r','\n'});
Or just plain Trim() like so
String output = buf.Substring(4).Trim();

Clipboard can copy a few words?

I'm weak in English so I hope you will understand this.
I learned yesterday that Clipboard is copy.
//textBox1.Text = "My name is not exciting";
Clipboard.SetText(textBox1.Text);
textBox2.Text = Clipboard.GetText();
This code copies your everything from the textbox1 and paste it in textbox2 right?
So it's possible to copy only a few words from textbox1 and paste it in textbox2?
If you don't understand, I'm want copy only a few words not all the line.
Even if this high level code still bring me :)
Clipboard.GetText(); will return the raw copied elements.
What you can do is save them to some variable:
string text = Clipboard().GetText();
Then do something with text, to get the elements you need:
textBox2.Text = text.Substring(0, 10); // An example.
The main idea to take away from this is, GetText() will give you a string. It's up to you to slice and dice that string any way you see fit and then make use of the results.
You don't need the Clipboard for this. Your user won't like that ;)
Just create a variable like this:
string box1Content = textBox1.Text;
textBox2.Text = boxContent;
You can even skip that variable.
If you really want to use the clipboard, your way is doing that.
For just getting some text out of the textbox you can either use substring or regular expressions.
http://msdn.microsoft.com/en-us/library/aka44szs.aspx
Good luck
Daniel, the substring method is a good one to use. You simply tell it where you want to take a piece of your text and it will create a new string of just that.
textBox1.Text = "MY name is not exciting";
//pretend you only want "not exciting" to show
int index = textBox1.Text.IndexOf("not");//get the index of where "not" shows up so you can cut away starting on that word.
string partofText = textBox1.Text.Substring(index);//substring uses the index (in this case, index of "not") to take a piece of the text.
Clipboard.SetText(partofText);
textBox2.Text = Clipboard.GetText();
To my mind is better idea to take selected text from text box.
I'm not sure witch kind of text box you are using but so show example on WPF you should use TextBox.SelectedText property.
I like linq. :-)
This is a example for splitting the string, enumerable it and concats in one:
textBox1.Text = "My name is not exciting";
int firstWord = 2;
int lastWord = 4;
string[] wordList = textBox1.Text.Split(new[] { ' ', '.', ',' }, StringSplitOptions.RemoveEmptyEntries);
string newText = string.Concat(wordList.Where((word, count) => count >= firstWord - 1 && count < lastWord).Select(w => w + " ")).TrimEnd();
Clipboard.SetText(newText);
textBox2.Text = Clipboard.GetText();
// Result: "name is not"
Edit: and without Clipboard you can use simply this Line
textBox2.Text = newText;

How to extract range of characters from a string

If I have a string such as the following:
String myString = "SET(someRandomName, \"hi\", u)";
where I know that "SET(" will always exists in the string, but the length of "someRandomName" is unknown, how would I go about deleting all the characters from "(" to the first instance of """? So to re-iterate, I would like to delete this substring: "SET(someRandomName, \"" from myString.
How would I do this in C#.Net?
EDIT: I don't want to use regex for this.
Providing the string will always have this structure, the easiest is to use String.IndexOf() to look-up the index of the first occurence of ". String.Substring() then gives you appropriate portion of the original string.
Likewise you can use String.LastIndexOf() to find the index of the first " from the end of the string. Then you will be able to extract just the value of the second argument ("hi" in your sample).
You will end up with something like this:
int begin = myString.IndexOf('"');
int end = myString.LastIndexOf('"');
string secondArg = myString.Substring(begin, end - begin + 1);
This will yield "\"hi\"" in secondArg.
UPDATE: To remove a portion of the string, use the String.Remove() method:
int begin = myString.IndexOf('(');
int end = myString.IndexOf('"');
string altered = myString.Remove(begin + 1, end - begin - 1);
This will yield "SET(\"hi\", u)" in altered.
I know it's been years, but .Net been has also evolved in the meantime.
Consider using range operator in case anyone looking here for an answer.
Assuming that Set( and \"hi\", u) is constant value (8 digit without the escapes):
var sub = myString[^4...^8];
myString.Replace(sub, replaceValue);
more examples and a good explanation in this article or of course in microsoft docs
This is pretty awful, but this will accomplish what you want with a simple linq statement. Just presenting as an alternative to the IndexOf answers.
string myString = "SET(someRandomName, \"hi\", 0)";
string fixedStr = new String( myString.ToCharArray().Take( 4 ).Concat( myString.ToCharArray().SkipWhile( c => c != '"' ) ).ToArray() );
yields: SET("hi", 0)
Note: the skip is hard-coded for 4 characters, you could alter it to skip over the characters in an array that contains them instead.
I assume you want to transform
SET(someRandomName, "hi", u)
into:
SET(u)
To achieve that, you can use:
String newString = "SET(" + myString.Substring(myString.LastIndexOf(',') + 1).Trim();
To explain this bit by bit:
myString.LastIndexOf(',')
will give you the index (position) of your last , character. Increment it by 1 to get the start index of the third argument in your SET function.
myString.Substring(myString.LastIndexOf(',') + 1)
The Substring method will eliminate all characters up to the specified position. In this case, we’re eliminating everything up to (and including) the last ,. In the example above, this would eliminate the SET(someRandomName, "hi", part, and leave us with u).
The Trim is necessary simply to remove the leading space character before your u.
Finally, we prepend SET( to our substring (since we had formerly removed it due to our Substring).
Edit: Based on your comment below (which contradicts what you asked in your question), you can use:
String newString = "SET(" + myString.Substring(myString.IndexOf(',') + 1).Trim();

C# Replacing part of string by start and end position

I have a string and I want to replace a part of it.
The tricky part is that that I can't use Regex.replace, because I only know the start and end positions of the data in the string.
For example, if the string looks like this:
I love cats, some more stuff here, we dont know how much more
And I have start=8 and end=11. And I want to replace that part to whatever I need to. This time lets say dogs so the new string will look like:
I love dogs, some more stuff here, we dont know how much more
How I could do that?
Simplest way:
string replaced = original.Substring(0, start) + replacementText +
original.Substring(end);
I had expected StringBuilder to have something which would do this, but I think you'd have to call Remove then Insert.
str.Substring(0, 8) + "replacement" + str.Substring(11);
It's not "elegant", but it works.
ReplaceAt(int index, int length, string replace)
Here's an extension method that doesn't use StringBuilder or Substring. This method also allows the replacement string to extend past the length of the source string.
//// str - the source string
//// index- the start location to replace at (0-based)
//// length - the number of characters to be removed before inserting
//// replace - the string that is replacing characters
public static string ReplaceAt(this string str, int index, int length, string replace)
{
return str.Remove(index, Math.Min(length, str.Length - index))
.Insert(index, replace);
}
When using this function, if you want the entire replacement string to replace as many characters as possible, then set length to the length of the replacement string:
"0123456789".ReplaceAt(7, 5, "Salut") = "0123456Salut"
Otherwise, you can specify the amount of characters that will be removed:
"0123456789".ReplaceAt(2, 2, "Salut") = "01Salut456789"
If you specify the length to be 0, then this function acts just like the insert function:
"0123456789".ReplaceAt(4, 0, "Salut") = "0123Salut456789"
I guess this is more efficient since the StringBuilder class need not be initialized and since it uses more basic operations.
Hope this help
string newString =
String.Concat(
originalString.Substring(0, start),
replacementText,
originalString.Substring(end));
OR
StringBuilder sb = new StringBuilder(originalString);
sb
.Remove(start, length)
.Insert(start, replacementText);
Not elegant but funny solution :
string myString = "I love cats, some more stuff here, we dont know how much more";
Regex expr = new Regex("cats");
int start = 8;
int end = 11;
Match m =expr.Match(myString);
if (m.Index == start-1 && m.Length == end - (start-1))
{
Console.WriteLine(expr.Replace(myString, "dogs"));
}
Just for fun with LINQ:
const string S = "I love cats, some more stuff here, we dont know how much more";
const string Dogs = "dogs";
var res = S
.Take(7)
.Concat(Dogs)
.Concat(S.Where((c, i) => i > 10));
var resultString = string.Concat(res);

String functions

I want to search for a given string, within another string (Ex. find if "something" exists inside "something like this". How can I do the following? :
Know the position in which "something" is located (in the curr. ex. this is = 0.
Extract everything to the left or to the right, up to the char. found (see 1).
Extract a substring beggining where the sought string was found, all the way to X amount of chars (in Visual Basic 6/VBA I would use the Mid function).
string searched = "something like this";
1.
int pos = searched.IndexOf("something");
2.
string start = searched.Substring(0, pos);
string endstring = searched.Substring(pos);
3.
string mid = searched.Substring(pos, x);
Have you looked at the String.SubString() method? You can use the IndexOf() method to see if the substring exists first.
Take a look at the System.String member functions, in particular the IndexOf method.
Use int String.IndexOf(String).
I would do something like this:
string s = "I have something like this";
//question No. 1
int pos = s.IndexOf("something");
//quiestion No. 2
string[] separator = {"something"};
string[] leftAndRightEntries = s.Split(separator, StringSplitOptions.None);
//question No. 3
int x = pos + 10;
string substring = s.Substring(pos, x);
I would avoid using Split, as it's designed to give you multiple results. I would stick with the code in the first example, though the second block should actually read...
string start = searched.Substring(0, pos);
string endstring;
if(pos < searched.Length - 1)
endstring = searched.Substring(pos + "something".Length);
else
endstring = string.Empty
The key difference is accounting for the length of the string to find (hence the rather odd-looking "something".Length, as this example is designed for you to be able to plop in your own variable).

Categories