Trying to create an array to find occurrence of character in a given String. Only allowed to use methods length and charAt from the class String

huangapple go评论77阅读模式
英文:

Trying to create an array to find occurrence of character in a given String. Only allowed to use methods length and charAt from the class String

问题

尝试创建一个数组来查找给定字符串中字符的出现次数。

public static void main(String[] args)
{
  String s1 = "java";
  char ch = 'a';
 
  System.out.println(indexOf(s1, ch));
}

public static int indexOf(String s, char ch)
{
  int count = 0;
  
  while (count < s.length())
  {
     if (s.charAt(count) == ch)
        return count;
        
     else
        count += 1;
  }
  return -1;
}

所以结果应该是 1 3。

英文:

Trying to create an array to find the occurrence of a character in a given String.

public static void main(String[] args)
{
  String s1 = &quot;java&quot;;
  char ch = &#39;a&#39;;
 
System.out.println(indexOf(s1, ch));
}

public static int indexOf(String s, char ch)
{
  int count = 0;
  
  while (count &lt; s.length())
  {
     if (s.charAt(count) == ch)
        return count;
        
     else
        count += 1;
  }
  return -1;
}

So the result is supposed to be 1 3

答案1

得分: 0

public static int[] indexOf(String s, char ch) {
    int count = 0;
    int[] result = new int[s.length()];
    for (int i = 0; i < result.length; i++) {
        if (s.charAt(i) == ch) {
            result[count] = i;
            count += 1;
        }
    }
    return Arrays.copyOf(result, count); // cut to keep indexes only
}

Demo

System.out.println(Arrays.toString(indexOf("java", 'a')));        // [1, 3]
System.out.println(Arrays.toString(indexOf("abahauayata", 'a'))); // [0, 2, 4, 6, 8, 10]
System.out.println(Arrays.toString(indexOf("aaaaaaabbbb", 'a'))); // [0, 1, 2, 3, 4, 5, 6]
英文:

To get all the indexes where a char occurs in a string, you need a value that marks the position in the string, and the other the nulber of matches, to know the position in the result array, and at the end, cut the array to remove the leading unused boxes

public static int[] indexOf(String s, char ch) {
    int count = 0;
    int[] result = new int[s.length()];
    for (int i = 0; i &lt; result.length; i++) {
        if (s.charAt(i) == ch) {
            result[count] = i;
            count += 1;
        }
    }
    return Arrays.copyOf(result, count); // cut to keep indexes only
}

Demo

System.out.println(Arrays.toString(indexOf(&quot;java&quot;, &#39;a&#39;)));        // [1, 3]
System.out.println(Arrays.toString(indexOf(&quot;abahauayata&quot;, &#39;a&#39;))); // [0, 2, 4, 6, 8, 10]
System.out.println(Arrays.toString(indexOf(&quot;aaaaaaabbbb&quot;, &#39;a&#39;))); // [0, 1, 2, 3, 4, 5, 6]

答案2

得分: 0

因为您有限制,您将需要首先创建一个大小等于字符串长度的数组(假设所有字符都相同)。然后,迭代给定字符串的字符,并存储找到与给定字符匹配的索引的位置。最后,将该数组的初始位置复制到另一个数组中,并返回相同的数组。如果没有找到匹配,简单地返回 new int[] { -1 }

示例:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // 测试
        String s1 = "java";
        char ch = 'a';

        int[] array = indexOf(s1, ch);
        System.out.println(Arrays.toString(array));

        array = indexOf(s1, 'x');
        System.out.println(Arrays.toString(array));
    }

    public static int[] indexOf(String s, char ch) {
        // 最大大小可以是字符串的长度,即所有字符都相同时
        int[] array = new int[s.length()];
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ch) {
                array[count++] = i;
            }
        }
        if (count == 0) {
            return new int[] { -1 };
        } else {
            // 创建一个大小为 count 的数组 result[],并将元素从 array[] 复制到其中
            int[] result = new int[count];
            for (int i = 0; i < count; i++) {
                result[i] = array[i];
            }
            return result;
        }
    }
}

输出:

[1, 3]
[-1]
英文:

Because of the restrictions you have, you will have to first create an array with the size equal to the length of the string (assuming a condition when all chars are same). Then, iterate the characters of the given string and store the index where a match with the given character is found. Finally, copy the initialised positions of this array to another array and return the same. In case, no match is found, simply return new int[] { -1 }.

Demo:

import java.util.Arrays;

public class Main {
	public static void main(String[] args) {
		// Test
		String s1 = &quot;java&quot;;
		char ch = &#39;a&#39;;

		int[] array = indexOf(s1, ch);
		System.out.println(Arrays.toString(array));

		array = indexOf(s1, &#39;x&#39;);
		System.out.println(Arrays.toString(array));
	}

	public static int[] indexOf(String s, char ch) {
		// The maximum size can be the length of the string i.e. when all chars are same
		int[] array = new int[s.length()];
		int count = 0;
		for (int i = 0; i &lt; s.length(); i++) {
			if (s.charAt(i) == ch) {
				array[count++] = i;
			}
		}
		if (count == 0) {
			return new int[] { -1 };
		} else {
			// Create an array result[], of the size = count and copy elements from array[]
			// to it
			int[] result = new int[count];
			for (int i = 0; i &lt; count; i++) {
				result[i] = array[i];
			}
			return result;
		}
	}
}

Output:

[1, 3]
[-1]

答案3

得分: 0

public static int[] indexOf(String s, char ch) {
    int total = 0;

    for (int i = 0; i < s.length(); i++)
        if (s.charAt(i) == ch)
            total++;

    if (total == 0)
        return new int[0];

    int[] res = new int[total];

    for (int i = 0, j = 0; i < s.length(); i++)
        if (s.charAt(i) == ch)
            res[j++] = i;

    return res;
}
英文:
public static int[] indexOf(String s, char ch) {
    int total = 0;

    for (int i = 0; i &lt; s.length(); i++)
        if (s.charAt(i) == ch)
            total++;

    if (total == 0)
        return new int[0];

    int[] res = new int[total];

    for (int i = 0, j = 0; i &lt; s.length(); i++)
        if (s.charAt(i) == ch)
            res[j++] = i;

    return res;
}

huangapple
  • 本文由 发表于 2020年10月27日 04:44:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/64544708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定