问题描述
你好朋友,
我尝试下面给出的代码它正常工作所有字符串(如这里是她的家试图找到他)但当我尝试anana是一个香蕉并试图找到ana这是抛出异常。请帮助我。
我尝试过:
Hello friends,
I tried below given code it is working fine with all strings(like "here is her home" trying to find "he") But when i am trying with "anana is an banana" and trying to find "ana" this is throwing exception. Please help my in this.
What I have tried:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringTest
{
class Program
{
static void Main(string[] args)
{
int count = 0, count1 = 0;
int i, j, l1, l2;
Console.WriteLine("Enter a string : ");
string str=Console.ReadLine();
Console.WriteLine("Enter a string : ");
string sub=Console.ReadLine();
l1 = str.Length; l2 = sub.Length;
for (i = 0; i < l1;)
{
j = 0;
count = 0;
while ( (j<l2)>
{
count++;
i++;
j++;
}
if (count == l2)
{
count1++;
count = 0;
}
else
i++;
}
Console.WriteLine("{0} occurs {1} times in {2}", sub, count1, str);
Console.ReadLine();
}
}
}
推荐答案
for (i = 0; i < l1;)
{
j = 0;
count = 0;
while ( (j<l2)>
{
count++;
i++;
j++;
}
if (count == l2)
{
count1++;
count = 0;
}
else
i++;
}
此代码正在使用指针和计数器,但就是这样。
使用改善问题更新你的问题。
问题:如果您输入香蕉并搜索 ana ,您应该出现多少次?
因为有两种可能性b ana na和ban ana ,但它们重叠。
This code is playing with pointers and counters, but that's all.
Use Improve question to update your question.
Question: if you have the input banana and search for ana, how many occurrences should you have ?
Be cause there is 2 possibilities banana and banana, but they overlap.
using System;
namespace StringTest
{
class Program
{
static void Main(string[] args)
{
// always define the variable names more understandable. it will be easier for debugging
int occurances = 0;
int inputLength, findLength;
Console.WriteLine("Enter a string : ");
string input = Console.ReadLine();
Console.WriteLine("Enter a string to find : ");
string find = Console.ReadLine();
inputLength = input.Length; findLength = find.Length;
// if you have only one line of code, next to 'for' and 'if' statements, its not mandatory to use '{','}' brackets as below.
for (int i = 0; i < inputLength; i++) // loop each character from the input string
if (inputLength >= i + findLength) // check the input length is greater than equal to loop index + find key length (validation, to avoid index exception in the next line )
if (find == input.Substring(i, findLength)) // match the finding key with the current instance (index + key length)
occurances++; // if the condition satisfies , do increament
Console.WriteLine("'{0}' occurs {1} times in '{2}'", find, occurances, input);
Console.ReadLine();
}
}
}
这篇关于如何计算另一个字符串中字符串的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!