简体   繁体   English

计算字符在字符串中以连续方式出现的次数

[英]Count the number of times a character appears in a contiguous manner in a string

I'm new to Java. 我是Java的新手。 I'm trying to print the characters present in the string along with their count. 我正在尝试打印字符串中的字符及其计数。 The count only increments when the same character is present next to it. 计数仅在旁边存在相同字符时递增。

Ex: 例如:

I/O : Sssgs I / O:Sssgs

O/P : S1s2g1s1 O / P:S1s2g1s1

Counting the occurence of each character gives the count of the full count regardless of the characters not being present next to each other. 计算每个字符的出现次数给出完整计数的计数,而不管彼此不存在的字符。 Tampering with the i & j loops gives an OutOfBounds error. 篡改i&j循环会产生OutOfBounds错误。

      //ch[] is the String converted to a character array.
     //count[] is an array to store count of the characters      

    //Checks if present char and next char are same and increments count
    for(int i=0;i<ch.length;i++)    
    {
        count[i]=0;
        for(int j=0;j<ch.length;j++)
        {
            if(ch[i]==ch[j])
            {
                count[i]++;
            }
        }
    }

    //Prints Distinct char
    for(int i=0;i<ch.length;i++)
    {
        int j;
        for(j=0;j<i;j++)
        {
            if(ch[i]==ch[j])
            {
                break;
            }
        }

        if(i==j)
        {
            System.out.print(ch[i]+" "+count[i]);
        }
    }

The Input is > HelloWorld 输入是> HelloWorld

The expected output should be > H1 e1 l2 o1 W1 o1 r1 l1 d1 预期输出应> H1 e1 l2 o1 W1 o1 r1 l1 d1

I just made some corrections in your code and below it is how it looks like: 我刚刚在你的代码中做了一些修正,下面是它的样子:

public static void main(String[] args) {
    String s = "Sssgs";
    char[] ch = s.toCharArray();
    int[] count = new int[20];

       for(int i=0;i<ch.length;i++)    
        {
            count[i]=0;
            for(int j=i;j<ch.length;j++)
            {
                if(ch[i]==ch[j])
                {
                    count[i]++;
                } else {
                    break;
                }
            }
        }

        //Prints Distinct char
        for(int i=0;i<ch.length;i += count[i])
        {
            System.out.print(ch[i] + "" +count[i]);
        }
}

Most changes was in Prints Distincts when I just read character and it number of occurence and then jump that number in iteration. 当我只读取字符及其出现次数然后在迭代中跳过该数字时,大多数更改都在Prints Distincts中。 It lets me stops on the next character which is different 它让我停止下一个不同的角色

The output for "Sssgs" is "S1s2g1s1" and for "HelloWorld" is "H1e1l2o1W1o1r1l1d1" “Sssgs”的输出为“S1s2g1s1”,“HelloWorld”的输出为“H1e1l2o1W1o1r1l1d1”

Here is a simpe solution that doesn't use any extra array and instead directly prints the counted char when the next one is different 这是一个简单的解决方案,不使用任何额外的数组,而是在下一个不同时直接打印计数的char

char prevChar = ch[0];
int count = 1;
for (int i = 1; i < ch.length; i++) {
  if (ch[i] != prevChar) {
    System.out.printf("%c%d ", prevChar, count);
    count = 1;
    prevChar = ch[i];
  } else {
    count++;
  }
}
System.out.printf("%c%d ", prevChar, count); 

I hate this solution, but I guess you are using a char[] because of needs. 我讨厌这个解决方案,但我猜你因为需要而使用char []。 If not compulsory, i would recommend you to use a StringBuilder as Lino suggested. 如果不是强制性的,我建议你使用StringBuilder作为Lino建议。

char blankChar = " ".charAt(0);
if (stringInput == null || "".equals(stringInput)) {
    System.out.println("Empty input");
}
char[] ch = stringInput.toCharArray();
char lastChar = ch[0];
int numAppearanceslastChar = 0;
for (char element : ch) {
    if (element == blankChar) {
        continue;
    }
    if (lastChar == element) {
        numAppearanceslastChar++;
    } else {
        System.out.print(lastChar+""+numAppearanceslastChar+" ");
        lastChar = element;
        numAppearanceslastChar = 1;
    }
}
System.out.println(lastChar+""+numAppearanceslastChar+" ");

Output: H1 e1 l2 o1 w1 o1 r1 l1 d1 输出: H1 e1 l2 o1 w1 o1 r1 l1 d1

Explanation: Read the whole word only once (note you wuere doing 3 times a for loop) and compare last read char with the new one. 说明:只读一遍整个单词(注意你做了3次for循环)并将最后读取的char与新的char进行比较。 If they match, increment the number of occurences of that char. 如果它们匹配,则增加该char的出现次数。 If they are not, then you print them and set the new characted as the last read. 如果不是,则打印它们并将新的chaaled设置为最后一次读取。 When you end reading the word, print the last char read. 当您结束阅读该单词时,打印最后一个char读取。

Always remember to keep it simple! 永远记得保持简单! And sanitize (you would get a nullPointer in this code if receiving a null or empty, just wrote it there to point it out). 并且清理(如果收到null或空,你会在这段代码中得到一个nullPointer,只需在那里写出来指出它)。

I came up with this: 我想出了这个:

public static String count(String in) {
    if (in == null || in.isEmpty()) {
        return in;
    }
    int length = in.length();
    if (length == 1) {
        return in + '1';
    }
    StringBuilder out = new StringBuilder(length << 1);

    char previous = in.charAt(0);
    int count = 1;
    for (int i = 1; i < length; i++) {
        char current = in.charAt(i);
        if (previous == current) {
            count++;
        } else {
            out.append(previous).append(count);
            previous = current;
            count = 1;
        }
    }
    return out.append(previous).append(count).toString();
}

Takes care of null and empty strings. 处理空字符串和空字符串。 And strings with length == 1 (which is just string + 1 ). 并且length == 1 string + 1 (只是string + 1 )。

This solution also doesn't need to create an additional char[] array, as it is working with charAt 此解决方案也不需要创建额外的char[]数组,因为它与charAt一起使用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何计算字符在字符串中出现的连续次数 - How to count consecutive times a character appears in a String 计算aaa在具有和重叠的字符串中出现的次数 - count number of times aaa appears in a string with and with overlaping 需要找到字符串中最频繁出现的字符并返回出现的次数 - Need to find the character most frequent in a string and return the number of times it appears JAVA中最后一个字符出现的次数只使用String - Number of times the last character appears in JAVA only use String Java程序查找在字符串中出现次数最多的字符? - Java program to find the character that appears the most number of times in a String? 在不使用映射的情况下如何计算字符串出现在数组中的次数? - How to count the number of times a string appears in an array without using maps? 编写一个程序来计算字符“a”出现在文件JavaIntro.txt中的任何位置的次数。 - Write a program to count the number of times that the character “a” appears anywhere in the file JavaIntro.txt. Java计算字符在文件中出现的次数 - Java counting the number of times a character appears in a file 如何计算“。”在网页中出现的次数? - How to count the number of times “.” appears in a webpage? 该方法应该计算“.”、“?”或“!”的次数。 出现在文中 - the method is supposed to count the number of times a ‘.’, ‘?’, or ‘!” appears in the text
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM