I want to remove all characters after the fourth space in a string.
Example:
Source: AAD BCCD QWD SDKE DJQWEK DJT
Result: AAD BCCD QWD SDKE
I tried to use 'String.indexof'. but, I couldn't.
Here is my code:
Result = source.Substring(source.IndexOf(string.Empty, source.IndexOf(string.Empty) + 3));
You could try this:
string result = string.Join(" ", source.Split(' ').Take(4));
This splits the original source string at each space character, takes the first 4 occurrences and concatenates them with a space character.
It will also work correctly in cases where there are less than 4 counts of spaces in the source string.
Maybe try this (if it's still actuall of course):
string Source = "AAD BCCD QWD SDKE DJQWEK DJT"
int space = GetNthIndex(Source, ' ', 4);
string result = sample.Substring(0, space);
You can make a loop with a counter and check each character. Pseudocode:
counter = 0;
foreach(character in string)
if(counter > 4)
exit;
else if(character == space)
counter++;
output character
else
output character
Related
I need to get the first char of this string:
String s = "X-4711";
And put it after the number with an ';' , like: 4711;X.
I already tried it with:
String x = s.Split("-")[1] + ";" + s.Split("-")[0];
then I get it, but can I do it better or is this the only possible way?
var items = s.Split ("-");
string x = String.Format ("{0};{1}", items[1], items[0]);
At most this makes it a little more readable and a micro-optimisation of only having to split once.
EDIT :
As some of the comments have pointed out, if you are using C#6 you can make use of String Interpolation to format the string. It does the exact same thing, only looks a little better.
var items = s.Split ("-");
string x = $"{items[1]};{items[0])}";
Not sure what performance you are looking for small string operations, your code is well written and satisfy your needs.
One minor thing you might consider is removing additional split performed on input string.
var subs = s.Split ("-");
String.Format ("{0};{1}", subs [1], subs [0]);
If you are looking single liner (crazy programmer), this might help.
string.Join(";", s.Split('-').Reverse())
String.Substring: Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.
string sub = input.Substring(0, 1);
string restStr = input.Substring(2, input.length-2);
// string restStr = input.Substring(2); Can also use this instead of above line
string madeStr = restStr + ";" + sub;
You call the Substring method to extract a substring from a string that begins at a specified character position and ends before the end of the string. The starting character position is a zero-based; in other words, the first character in the string is at index 0, not index 1. To extract a substring that begins at a specified character position and continues to the end of the string, call the Substring method.
I have a string that has numbers dash and numbers so it can be
1-2
234-45
23-8
It can be any sequence of any number up to 12 characters.
These all numbers are preceded by a string. I need to extract this string before this sequence begins.
This is a Test1 1-2
This is a test for the first time 234-45
This is a test that is good 23-8
so I need to extract
This is a Test1
This is a test for the first time
This is a test that is good
there is only one space between this string and the sequence.
Is there any way I can extract that string. Split method is not working here.
I forgot to mention that I have numbers/test before the string too so it can be
2123 This is a test for the first time 23-456
or
Ac23 This is a test for the first time 23-457
any help will be appreciated.
Here's one way:
var sample = "2123 This is a Test1 1-2";
// Find the first occurrence of a space, and record the position of
// the next letter
var start = sample.IndexOf(' ') + 1;
// Pull from the string everything starting with the index found above
// to the last space (accounting for the difference from the starting index)
var text = sample.Substring(start, sample.LastIndexOf(' ') - start);
After this, text should equal:
This is a Test1
Wrap it up in a nice little function and send your collection of strings through it:
string ParseTextFromLine(string input)
{
var start = input.IndexOf(' ') + 1;
return input.Substring(start, input.LastIndexOf(' ') - start);
}
This is pretty easy,
string s = "This is a Test1 1-2";
s = s.Substring(0,s.LastIndexOf(" ");
and now s will be "This is a Test1"
I have a field that is displayed inside a div and the problem is that it doesn't break line if a user puts in a string thats longer then the number of characters that can fit outside the line within a div, it basically stretches outside the div. How can I insert a space in every word 'thats in a string' that has a seuqence of 20 characters or more without a space between . For example, now I am doing something like this
string words
Regex.Replace(words, "(.{" + 20 + "})", "$1" + Environment.NewLine);
But that just inserts a line break at every 20 character oppose to a sequence without a space. I am really not that good with regular expressions so the code above is something I found.
Would a CSS solution work better?
word-wrap:break-word;
example:
http://jsfiddle.net/45Fq4/
To solve this with regex you could use #"(\S{20})" as your pattern.
\S will match any non-whitespace character which I believe fits your criteria since it will then only work if it finds 20 or more non-whitespace characters in a row.
Example usage is:
string words = "It should break after \"t\": abcdefghijklmnopqrstuvwxyz";
string output = Regex.Replace(words, #"(\S{20})", "$1" + Environment.NewLine);
this code worked for me:
string words
string outputwords = words;
int CharsWithoutSpace = 0;
for (int i = 0; i < outputwords.Length; i++)
{
if (outputwords[i] == ' ')
{
CharsWithoutSpace = 0;
}
else
{
CharsWithoutSpace++;
if (CharsWithoutSpace >= 20)
{
outputwords = outputwords.Insert(i + 1, Environment.NewLine);
CharsWithoutSpace = 0;
}
}
}
Console.WriteLine(outputwords);
Quick little question...
I need to count the length of a string, but WITHOUT the spaces inside of it.
E.g. for a string like "I am Bob", string.Length would return 8 (6 letters + 2 spaces).
I need a method, or something, to give me the length (or number of) just the letters (6 in the case of "I am Bob")
I have tried the following
s.Replace (" ", "");
s.Replace (" ", null);
s.Replace (" ", string.empty);
to try and get "IamBob", which I did, but it didn't solve my problem because it still counted "" as a character.
Any help?
This returns the number of non-whitespace characters:
"I am Bob".Count(c => !Char.IsWhiteSpace(c));
Demo
Char.IsWhiteSpace:
White space characters are the following Unicode characters:
Members of the SpaceSeparator category, which includes the characters SPACE (U+0020), OGHAM SPACE MARK (U+1680), MONGOLIAN VOWEL SEPARATOR (U+180E), EN QUAD (U+2000), EM QUAD (U+2001), EN SPACE (U+2002), EM SPACE (U+2003), THREE-PER-EM SPACE (U+2004), FOUR-PER-EM SPACE (U+2005), SIX-PER-EM SPACE (U+2006), FIGURE SPACE (U+2007), PUNCTUATION SPACE (U+2008), THIN SPACE (U+2009), HAIR SPACE (U+200A), NARROW NO-BREAK SPACE (U+202F), MEDIUM MATHEMATICAL SPACE (U+205F), and IDEOGRAPHIC SPACE (U+3000).
Members of the LineSeparator category, which consists solely of the LINE SEPARATOR character (U+2028).
Members of the ParagraphSeparator category, which consists solely of the PARAGRAPH SEPARATOR character (U+2029).
The characters CHARACTER TABULATION (U+0009), LINE FEED (U+000A), LINE TABULATION (U+000B), FORM FEED (U+000C), CARRIAGE RETURN (U+000D), NEXT LINE (U+0085), and NO-BREAK SPACE (U+00A0).
No. It doesn't.
string s = "I am Bob";
Console.WriteLine(s.Replace(" ", "").Length); // 6
Console.WriteLine(s.Replace(" ", null).Length); //6
Console.WriteLine(s.Replace(" ", string.Empty).Length); //6
Here is a DEMO.
But what are whitespace characters?
http://en.wikipedia.org/wiki/Whitespace_character
You probably forgot to reassign the result of Replace. Try this:
string s = "I am bob";
Console.WriteLine(s.Length); // 8
s = s.Replace(" ", "");
Console.WriteLine(s.Length); // 6
A pretty simple way is to write an extension method that will do just that- count the characters without the white spaces. Here's the code:
public static class MyExtension
{
public static int CharCountWithoutSpaces(this string str)
{
string[] arr = str.Split(' ');
string allChars = "";
foreach (string s in arr)
{
allChars += s;
}
int length = allChars.Length;
return length;
}
}
To execute, simply call the method on the string:
string yourString = "I am Bob";
int count = yourString.CharCountWithoutSpaces();
Console.WriteLine(count); //=6
Alternatively, you can split the string an way you want if you don't want to include say, periods or commas:
string[] arr = str.Split('.');
or:
string[] arr = str.Split(',');
this is fastest way:
var spaceCount = 0;
for (var i 0; i < #string.Lenght; i++)
{
if (#string[i]==" ") spaceCount++;
}
var res = #string.Lenght-spaceCount;
Your problem is probably related to Replace() method not actually changing the string, rather returning the replaced value;
string withSpaces = "I am Bob";
string withoutSpaces = withSpaces.Replace(" ","");
Console.WriteLine(withSpaces);
Console.WriteLine(withoutSpaces);
Console.WriteLine(withSpaces.Length);
Console.WriteLine(withoutSpaces.Length);
//output
//I am Bob
//IamBob
//8
//6
You can use a combination of Length and Count functions on the string object. Here is a simple example.
string sText = "This is great text";
int nSpaces = sText.Length - sText.Count(Char.IsWhiteSpace);
This will count single or multiple (consistent) spaces accurately.
Hope it helps.
I have a large string and it’s stored in a string variable, str. And I want to get a substring from that in C#.
Suppose the string is: " Retrieves a substring from this instance. The substring starts at a specified character position, "
The substring result what I want to display is: The substring starts at a specified character position.
You could do this manually or using the IndexOf method.
Manually:
int index = 43;
string piece = myString.Substring(index);
Using IndexOf, you can see where the full stop is:
int index = myString.IndexOf(".") + 1;
string piece = myString.Substring(index);
string newString = str.Substring(0, 10);
will give you the first 10 characters (from position 0 to position 9).
See String.Substring Method.
Here is an example of getting a substring from the 14th character to the end of the string. You can modify it to fit your needs.
string text = "Retrieves a substring from this instance. The substring starts at a specified character position.";
// Get substring where 14 is the start index
string substring = text.Substring(14);
Making the assumption that you want to split on the full stop (.), then here's an approach that would capture all occurrences:
// Add # to the string to allow split over multiple lines
// (for display purposes to save the scroll bar from
// appearing on a Stack Overflow question :))
string strBig = #"Retrieves a substring from this instance.
The substring starts at a specified character position. great";
// Split the string on the full stop, if it has a length>0
// then, trim that string to remove any undesired spaces
IEnumerable<string> subwords = strBig.Split('.')
.Where(x => x.Length > 0).Select(x => x.Trim());
// Iterate around the new 'collection' to sanity check it
foreach (var subword in subwords)
{
Console.WriteLine(subword);
}
string text = "Retrieves a substring from this instance. The substring starts at a specified character position. Some other text";
string result = text.Substring(text.IndexOf('.') + 1,text.LastIndexOf('.')-text.IndexOf('.'))
This will cut the part of string which lays between the special characters.
A better solution using index in C# 8:
string s = " Retrieves a substring from this instance. The substring starts at a specified character position, ";
string subString = s[43..^2]; // The substring starts at a specified character position
var data =" Retrieves a substring from this instance. The substring starts at a specified character position.";
var result = data.Split(new[] {'.'}, 1)[0];
Output:
Retrieves a substring from this instance. The substring starts at a
specified character position.
All answers used the main string that decrease performance. You should use Span to have better performance:
var yourStringSpan = yourString.AsSpan();
int index = yourString.IndexOf(".") + 1;
string piece = yourStringSpan.slice(index);
It's easy to rewrite this code in C#...:
This method works if your value is between two substrings!
For example:
stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"
The calls should be:
myNameValue = SplitStringByASubstring(stringContent, "[myName]")
colorValue = SplitStringByASubstring(stringContent, "[color]")
etcValue = SplitStringByASubstring(stringContent, "[etc]")