For example say I have this string of text, that is greater than 70 characters(including spaces):
"Water is made up of hydrogen and oxygen, and it exists in gaseous, liquid and solid states. Water is one of the most plentiful and essential compounds, occurring as a liquid on Earth's surface under normal conditions, which makes it invaluable for human uses and as plant and animal habitat."
I want shorten this string only up to 70 characters and then add the ellipsis(...) at the end. So I applied the following code:
public static void MyDescription(string str){
if(str.Length > 70){
str = str.Substring(0,70) "...";
}
Console.Writeline(str);
}
The problem I see with is, that it's cutting of the words in the middle like this at the end:
"Water is made up of hydrogen and oxygen, and it exists in gaseous, li
Instead I want it to display:
Water is made up of hydrogen and oxygen, and it exists in gaseous, liquid
Is there a way to not cut off the word and complete the word?
CodePudding user response:
You can do something like:
if(str.Length > 70) {
// You may want to put this array in a class as a static readonly field
char[] wordEndings = { ' ', ',', '.' };
int endOfWord = str.IndexOfAny(wordEndings, 70);
// It's the last word
if(endOfWord == -1) {
endOfWord = str.Length;
}
str = str.Substring(0, endOfWord);
}
You will need to fine-tune this some more based on your use case, and some edge cases it doesn't account for
CodePudding user response:
if (str <= 70) return str;
var words = str.Split(' ');
var charCount = 0;
for (int i = 0; i < words.Length; i ) {
var word = words[i];
charCount = word.Count 1; // 1 for a space
if (charCount > 70) {
// if you don't want to exceed 70, charCount -= word.Length;
break;
}
}
return str.SubString(0, charCount) "...";
This assumes there are atleast 2 words, separated by 'regular' space characters. If you no spaces, this will give unexpected results. If this is the case, check if there are any spaces at all before doing the above.