Change the second character in a string [duplicate] - c#

This question already has answers here:
how to change nth element of the string
(5 answers)
Closed 5 years ago.
string input = "testeeeeeee";
char[] temp = input.ToCharArray();
var test = Regex.Replace(input.Replace(temp[1].ToString(), "#").Trim(), #"\s+", " ");
Console.WriteLine(test);
This is the code I have now, I want my second char on a string to be replaced with "#" , now is the problem that every e will be replaced in # , how to fix it that only the second char will be replaced and nothing more?

One way is to just assign a new value to the second char:
var input = "testeeeeeee".ToCharArray();
input[1] = '#';
var result = new string(input);
You'd want to do something like input[1] = # on the original string and not the char[] but as strings are immutable you cannot change it and the indexer is read-only.
Another way (which I think is less advisable):
var input = "testeeeeeee";
var result = input[0] + "#" + string.Concat(input.Skip(2));
For the second way it is cleaner to use SubString to get the string from the second index until the end

You can use the Substring function
string input = "testeeeeeee";
string new_input = input.Substring(0, 1) + "#" + input.Substring(2, input.Length)

Related

get the characters before and after certain character having variable length [duplicate]

This question already has answers here:
Split string and get Second value only
(5 answers)
Closed 3 years ago.
I am trying to get the characters that appear before and after certain character ("-").
string val = "7896-2-5";
7896-2-5 here I want to get the character that appear between the two dashes i.e. 2
string val = "4512-12-5";
4512-12-5 so here 12,
the position of first appearance of - is fixed from left side but the position of second appearance of - is determined by the character in between the two - , may be single digit or double digit number.
How can I get the characters?
Easiest would be to use string.Split('-')
e.g.
var middleDigit = string.Split('-')[1];
if your string should have tow dashes try this:
string myString = "4512-12-5";
string result="";
if(myString.Count(f => f =='-') == 2)
result = myString.Substring(myString.IndexOf('-') + 1 ,myString.LastIndexOf('-') - myString.IndexOf('-') - 1);
else
result = "string is not well formated";
Console.WriteLine(result);

How can I parse out the first three words from a string? [duplicate]

This question already has answers here:
get only 3 words of a String in C#
(2 answers)
Closed 4 years ago.
I have this string:
var a = "a new test string today";
How can I parse a to make another string that contains just the words
"a new test"
You could do this in a number of ways.
For example: Using Split, LINQ and Join
string.Join(" ", a.Split(' ').Take(3));
Or by finding the third space:
var firstSpace = a.IndexOf(' ');
var secondSpace = a.IndexOf(' ', firstSpace + 1);
var thirdSpace = a.IndexOf(' ', secondSpace + 1);
result = a.Substring(0, thirdSpace);
Error handling omitted.

Substring in c# to find second part in the string [duplicate]

This question already has answers here:
How can I split a string with a string delimiter? [duplicate]
(7 answers)
Closed 4 years ago.
How to find the second part of the string using substring in c#
I have follwwing string:
string str = "George Micahel R - 412352434";
I wanted the above string as two parts.Before "-" and after "-"
I have my first part using following code:
string firstPart = str.Substring(0,str.IndexOf(" - "));
When I am trying for the second part using the following code it gives me an error.
string secondPart = str.Substring(str.IndexOf(" - "), Len(str);
How to get the second part(only number)?
Thanks in advance.
Simply use split function:
var splittedArray = str.Split('-');
var leftPart = splittedArray[0];
var rightPart = splittedArray[1];
Use the Split() method instead.
string str = "George Micahel R - 412352434";
string[] words = str.Split('-');
Console.WriteLine(words[0].Trim()); # George Micahel R
Console.WriteLine(words[1].Trim()); # 412352434

Getting second word of a string in c# [duplicate]

This question already has answers here:
Split string and get first value only
(4 answers)
Closed 7 years ago.
I have declared a string and i want to get the second word from the string. For eg.
string str = "Hello world";
And I want to get the word "world" from str.
The simplest answer is to Split on space, and take the second item:
var secondWord = str.Split(' ').Skip(1).FirstOrDefault();
I use FirstOrDefault here so you get a valid null result for input of just one word.
The downside though is it will parse the entire string, so this is not a good suggestion if you want the second word of a book.
Or, you can make use of IndexOf to find the first and second occurrence of space, then Substring to take that portion:
static string GetSecondWord(string str)
{
var startIndex = str.IndexOf(' ') + 1;
if (startIndex == 0 || startIndex == str.Length)
return null;
var endIndex = str.IndexOf(" ", startIndex, StringComparison.CurrentCulture);
if (endIndex == -1)
endIndex = str.Length - 1;
return str.Substring(startIndex, endIndex - startIndex + 1);
}
This only looks through as many characters as you need, then copies out the portion you want in the end. It will perform better than the above. But it probably doesn't matter unless you're cataloging the second word of every book ever published.
Or, do it the old-fashioned way. Go through each character until you find the first space, then keep characters until the next one or the end of the string:
var sb = new StringBuilder();
bool spaceFound = false;
foreach(var c in str)
{
if(c == ' ')
{
if (spaceFound) //this is our second space so we're done
break;
spaceFound = true;
}
else
{
if (!spaceFound) //we haven't found a space yet so move along
continue;
sb.Append(c);
}
}
var secondWord = sb.ToString();
This method should be comparable in performance to the second one. You could accomplish the same thing using an enumerator instead of a foreach loop, but I'll leave that as an exercise for the reader. :)
You can do this. I suggest doing search before asking simple questions.
str.Split(' ')[1]
Demo code
Please note you have to include validations to your input, like string has more than one word, etc..
This is the perfect answer I think
//single space(or)
string line = "Hello world";
//double space(or)
string line = "Hello world";
//multiple space(or)
string line = "Hello world";
//multiple Strings
string line = "Hello world Hello world";
//all are working fine
string[] allId = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string finalstr = allId[allId.Length-1];

Split a string in between two characters in C#

I have a string of type "24;#usernamehere,#AWRFR\user,#,#,#usernamehere"
I want to split this string on the first appearance on # and , i.e i want a string to be fetched which is inbetween these two characters.
So for the above string i want the OUTPUT as:
usernamehere
How can i split a string in between two characters using Regex function?
A simple Regex Pattern might do the job:
var pattern = new System.Text.RegularExpressions.Regex("#(?<name>.+?),");
test:
string s = #"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
pattern.Match(s).Groups["name"].Value; //usernamehere
Using Linq:
using System.Linq;
var input = #"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
You can split it with a single line:
var x = input.Split('#').Where(e => e.Contains(',')).Select(e => e.Split(',').First());
which is the same as:
var x = from e in input.Split('#')
where e.Contains(',')
select e.Split(',').First();
in both cases the result would be:
x = {"usernamehere", "AWRFR\user", "", ""}
Which is exactly an array with all substrings enclosed by # and ,.
Then if you want the first element just add .First() or do:
x.First();
You need to find the first index of '#' & ','. Then use substring method to get your required trimmed string. Read this for more details on substring method
string s = #"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
string finalString = s.Substring(s.IndexOf('#') + 1, s.IndexOf(',') - s.IndexOf('#') - 1);
Not exactly the way you asked for it, but should do what you want...
string input = #"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
string username = input.Substring(input.LastIndexOf("#") + 1);
If you wanted you could get the position of the first # and the ,
int hashPosition = input.IndexOf("#") + 1;
int commaPosition = input.IndexOf(",");
string username = input.Substring(hashPosition, commaPosition - hashPosition));

Categories